源地址:http://f.ftkey.com/?p=61
测试用的图片
CGFloat size = 80.0f * [ [ UIScreen mainScreen] scale] ;
NSInteger i = ( 50 * indexPath.section) + indexPath.row;
item.imageURL = [ NSURL URLWithString: [ NSString stringWithFormat: @ "http://www.gravatar.com/avatar/%i?s=%0.f&d=identicon" , i, size] ] ;
xcode 3.x 时代: 更改xcode缺省公司名 __MyCompanyName__ :
defaults write com.apple.Xcode PBXCustomTemplateMacroDefinitions '{"ORGANIZATIONNAME" = "ftkey.com";}'
xcode 4.x 时代:
// 在地址簿中设定我的名片和添加公司名,现在再回到Xcode4看看,嘿嘿。
SVN Checkout Command-line :
// 最新版:
svn checkout http: //xxx.googlecode.com/svn/trunk/ xxx
// 带版本号:
svn co - r 1000 http: //forge.voodooprojects.org/svn/chameleon/trunk/
iPhone 应用中直接连接到特定的app store应用页面 :
[ [ UIApplication sharedApplication] openURL: [ NSURL URLWithString: @ "程序的相应连接" ] ] ;
宏定义,是否高清屏 是否iPad 是否模拟器 :
// 是否高清屏
#define isRetina ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)
// 是否iPad
#define isPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
// 是否模拟器
#define isSimulator (NSNotFound != [[[UIDevice currentDevice] model] rangeOfString:@"Simulator"].location)
// 推荐的宏命令
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
if ( UI_USER_INTERFACE_IDIOM( ) == UIUserInterfaceIdiomPhone) {
// iPhone 3.2以上的SDK
} else {
// iPad
}
#else
// iPhone 3.2以下的SDK
#endif
XML代理这个问题:
#if __IPHONE_4_0 && __IPHONE_4_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED
@interface TTMarkupStripper : NSObject <NSXMLParserDelegate> {
#else
@interface TTMarkupStripper : NSObject {
#endif
Objective 2.0 存取方式 (可以复写,测试发现 nil 是不会被retain的,但是可以再delloc方法中release一下,也不会出错,这个不懂…)
- ( NSString * ) value {
return value;
}
- ( void ) setValue: ( NSString * ) newValue {
if ( value != newValue) {
[ value release] ;
value = [ newValue retain] ; /* Or copy, if appropriate. 编程指南-官方教程 */
}
}
随机数 (0~100) :
或者:
srandom( time ( NULL ) ) ; int r = random( ) % 100 ;
iPhone/iPad:针对不同设备,使用不同CSS :
if( ( navigator.userAgent .match( /iPhone/i) ) || ( navigator.userAgent .match( /iPod/i) ) ) {
document.write( '' ) ;
}
if( ( navigator.userAgent .match( /iPad/i) ) ) {
document.write( '' ) ;
}
获取Image,内存控制由系统控制,非常不好!(当然这个必须是很少调用的,临时的,如果你是界面素材,一定用这个imageNamed,100张图片加载也会很快,要是你用代替方法来获取,那速度相当慢啊~~~~)
UIImage * myImage = [ UIImage imageNamed: @ "icon.png" ] ;
代替方法:
NSString * bundleImagePath = [ [ NSBundle mainBundle] pathForResource: @ "icon" ofType: @ "png" ] ;
UIImage * myImage = [ UIImage imageWithContentsOfFile: bundleImagePath] ; //(autorelease)
NSArray * paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES ) ;
NSString * docPath= [ paths lastObject] ; // "~/Documents"
NSString * docImagePath = [ docPath stringByAppendingPathComponent: @ "icon.png" ] ;
UIImage * myDocImage = [ UIImage imageWithContentsOfFile: docImagePath] ;//(autorelease)
NSURL * url = [ NSURL URLWithString: @ "http://xxx.jpg" ] ;
UIImage * myURLImage = [ UIImage imageWithData: [ NSData dataWithContentsOfURL: url] ] ;//(autorelease)
动画 :
// 普通动画:
CGContextRef context = UIGraphicsGetCurrentContext( ) ;
[ UIView beginAnimations: @ "View" context: context] ;
[ UIView setAnimationCurve: UIViewAnimationCurveEaseInOut] ;
[ UIView setAnimationDuration: 1.0 ] ;
// 看你的了.
[ UIView setAnimationDelegate: self] ;
[ UIView setAnimationWillStartSelector: @selector ( animationWillStart: ) ] ;
[ UIView setAnimationDidStopSelector: @selector ( animationFinish: finished: context: ) ] ;
[ UIView commitAnimations] ;
- ( void ) animationFinish: ( NSString * ) animationID finished: ( NSNumber * ) finished context: ( void * ) context {
if ( animationID == @ "View" ) {
[ myView removeFromSuperview] ;
}
}
// iPhone OS 4.0 and later. 已经放弃这种动画代理了!!!
居然用Block来代替
[ UIView animateWithDuration: 0.3 delay: 0 options: UIViewAnimationOptionCurveLinear
animations:^ {
settingView.center = CGPointMake( myView.center.x, myView.center.y+ 480.0 ) ;
}
completion:^ ( BOOL finished) {
if ( finished) {
[ myView removeFromSuperview] ;
}
}
] ;
// 模态动画,可以设置多种累加效果:
[ UIView beginAnimations: nil context: nil ] ;
// 看你的了.
[ UIView commitModalAnimations] ;
// 暂停,关键!!!!
[ NSThread sleepUntilDate: [ NSDate dateWithTimeIntervalSinceNow: 1.0f] ] ;
[ UIView beginAnimations: nil context: nil ] ;
// 看你的了.
[ UIView commitModalAnimations] ;
// 逐帧动画:
NSMutableArray * bflies = [ NSMutableArray array] ;
for ( int i = 1 ; i <= 10 ; i++ ) {
NSString * path = [ [ NSBundle mainBundle] pathForResource: [ NSString stringWithFormat: @ "bf_%d" , i] ofType: @ "png" ] ;
[ bflies addObject: [ UIImage imageWithContentsOfFile: path] ] ;
}
UIImageView * butterflyView = [ [ UIImageView alloc] initWithFrame: CGRectMake( 40.0f, 300.0f, 60.0f, 60.0f) ] ;
butterflyView.tag = 300 ;
butterflyView.animationImages = bflies;
butterflyView.animationDuration = 0.75f;
[ self.view addSubview: butterflyView] ;
[ butterflyView startAnimating] ;
[ butterflyView autorelease] ;
Layer 图层圆角、边框 、底纹其他常用操作:
#import <QuartzCore/QuartzCore.h> // 添加系统框架
layer.backgroundColor = [ UIColor cyanColor] .CGColor; // 给图层添加背景色
layer.contents = ( id ) [ UIImage imageNamed: @ "view_BG.png" ] .CGImage; // 给图层添加背景图片
layer.cornerRadius = 8 ; // 将图层的边框设置为圆脚
layer.masksToBounds = YES ; // 隐藏边界
layer.borderWidth = 5 ; // 给图层添加一个有色边框
layer.borderColor = [ UIColor colorWithRed: 0.52 green: 0.09 blue: 0.07 alpha: 1 ] .CGColor;
layer.shadowOffset = CGSizeMake( 0 , 3 ) ; // 设置阴影的偏移量
layer.shadowRadius = 10.0 ; // 设置阴影的半径
layer.shadowColor = [ UIColor blackColor] .CGColor; // 设置阴影的颜色为黑色
layer.shadowOpacity = 0.9 ; // 设置阴影的不透明度
使用UIImagePickerController调用系统照相机:
- ( void ) addPicEvent
{
//先设定sourceType为相机,然后判断相机是否可用(ipod)没相机,不可用将sourceType设定为相片库
UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
if ( ! [ UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera] ) {
sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
UIImagePickerController * picker = [ UIImagePickerController alloc] init] autorelease] ;
picker.delegate = self;
picker.allowsEditing = YES ;
picker.sourceType = sourceType;
[ self presentModalViewController: picker animated: YES ] ;
}
- ( void ) saveImage: ( UIImage * ) image {
NSLog( @ "保存" ) ;
[ image release] ; // 释放之前retain的Image
}
#pragma mark –
#pragma mark Camera View Delegate Methods
- ( void ) imagePickerController: ( UIImagePickerController * ) picker didFinishPickingMediaWithInfo: ( NSDictionary * ) info {
[ picker dismissModalViewControllerAnimated: YES ] ;
UIImage * image = [ [ info objectForKey: UIImagePickerControllerEditedImage] retain] ; //防止被系统释放
[ self performSelector: @selector ( saveImage: ) withObject: image afterDelay: 0.5 ] ;
}
- ( void ) imagePickerControllerDidCancel: ( UIImagePickerController * ) picker {
NSLog( @ "取消" ) ;
[ picker dismissModalViewControllerAnimated: YES ] ;
}
iPhone读写Txt文件 :
NSString * path = @ "xxx" ; //获取文件路径
NSData * reader = [ NSData dataWithContentsOfFile: path] ; // 读取文件十六进制内容
NSString * file = [ [ [ NSString alloc] initWithData: reader encoding: NSUTF8StringEncoding] autorelease] ; // 编码
NSMutableData * writer = [ [ [ NSMutableData alloc] init] autorelease] ; //创建数据缓冲
[ writer appendData: [ file dataUsingEncoding: NSUTF8StringEncoding] ] ; //将字符串添加到缓冲中
[ writer writeToFile: path atomically: YES ] ; //将缓冲的数据写入到文件中
一个逻辑性很强的,可以提高性能的,但是一直被遗忘的简单IF,很搞啊~
- ( void ) setAutoresize: ( BOOL ) flag {
if ( flag != _flag) { // _flag: H定义的成员 flag: 传入的值 。如果不相同时才做以下动作。
_flag = flag;
if ( _flag) { // 成员的值为真的时候
}
else { // 成员的值为假的时候
}
}
else { // 如果相同时(代表以前做过了,或者正在做某事)就根本不用做任何事情
}
}
stringWithFormat 格式化类似这种: Card001 Card002 Card003 … Card100
[ NSString stringWithFormat: @ "Card%03d" , i] ;
格式化位数
NSString * string1 = [ NSString stringWithFormat: @ "A string: %@, a float: %1.2f" , @ "string" , 31415.9265 ] ;
// string1 is "A string: string, a float: 31415.93"
// 批量发送Selector
[ [ self.view subviews] makeObjectsPerformSelector: @selector ( removeFromSuperview) ] ; // 批量移除superview
// 快速输出YES,NO
NSLog( res ? @ "YES" : @ "NO" ) ;
// UIAlertView中的UITableView大小
UIAlertView * messageAlertView = [ [ UIAlertView alloc] initWithTitle: @ "相关站点" message: @ "\n \n \n \n \n \n \n \n \n \n \n \n \n " delegate: nil cancelButtonTitle: @ "取消" otherButtonTitles: @ "默认" ,nil ] ;
UITableView * smartTipsTableView = [ [ UITableView alloc] initWithFrame: CGRectMake( 13 , 60 , 258 , 235 ) style: UITableViewStylePlain] ;
smartTipsTableView.backgroundColor = [ UIColor redColor] ;
[ messageAlertView show] ;
[ messageAlertView addSubview: smartTipsTableView] ;
[ smartTipsTableView autorelease] ;
[ messageAlertView autorelease] ;
// release时去掉NSLog的方法
#ifndef __OPTIMIZE__
# define NSLog(...) NSLog(__VA_ARGS__)
#else
# define NSLog(...) {}
#endif
// 让视图超出bound,可以前后预览的效果
scrollView.clipsToBounds = NO ;
// 系统自带的软件普通调用,可惜商家不喜欢,哎,都喜欢一个软件里面集成很多很多功能,都是为了利益。。。
+ ( void ) openEmail: ( NSString * ) address {
NSString * url = [ NSString stringWithFormat: @ "mailto://%@" , address] ;
[ [ UIApplication sharedApplication] openURL: [ NSURL URLWithString: url] ] ;
}
+ ( void ) openPhone: ( NSString * ) number {
NSString * url = [ NSString stringWithFormat: @ "tel://%@" , number] ;
[ [ UIApplication sharedApplication] openURL: [ NSURL URLWithString: url] ] ;
}
+ ( void ) openSms: ( NSString * ) number {
NSString * url = [ NSString stringWithFormat: @ "sms://%@" , number] ;
[ [ UIApplication sharedApplication] openURL: [ NSURL URLWithString: url] ] ;
}
+ ( void ) openBrowser: ( NSString * ) url {
[ [ UIApplication sharedApplication] openURL: [ NSURL URLWithString: url] ] ;
}
+ ( void ) openMap: ( NSString * ) address {
NSString * addressText = [ address stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding] ;
NSString * url = [ NSString stringWithFormat: @ "http://maps.google.com/maps?q=%@" , addressText] ;
[ [ UIApplication sharedApplication] openURL: [ NSURL URLWithString: url] ] ;
}
- ( id ) init {
self = [ super initWithNibName: NSStringFromClass( [ self class] ) bundle: nil ] ;
if ( self == nil ) return nil ;
return self;
}
修改iOS控件,导航控制器、标签控制器的标题
// 导航标题
UIViewController.navigationItem.title = @ "Q&A" ;
// 下面分组的标题
UIViewController.tabBarItem.title = @ "Q&A" ;
// 而不是:
UINavigationController.tabBarItem.title = @ "Q&A" ; UITabBar.tabBarItem.title = @ "Q&A" ;
// 这样的用法 会让 UITabBarController一起生效:
self.title = @ "Q&A" ;
修改导航后退的按钮的名称,父ViewController设置,不是当前的。。。
// create a custom navigation bar button and set it to always say "back"
UIBarButtonItem * temporaryBarButtonItem= [ [ UIBarButtonItem alloc] init] ;
temporaryBarButtonItem.title= @ "Back" ;
self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
[ temporaryBarButtonItem release] ;
设置导航条透明
[ [ newNavController navigationBar] setBarStyle: UIBarStyleDefault] ;
[ [ newNavController navigationBar] setTranslucent: YES ] ;
解决偏移问题
UIViewController.wantsFullScreenLayout = YES ;
交换selector
#include <objc/runtime.h>
Method originalMethod = class_getInstanceMethod( [ self class] , @selector ( drawRect: ) ) ;
Method fixedMethod = class_getInstanceMethod( [ self class] , @selector ( ie_customDrawRect: ) ) ;
method_exchangeImplementations( originalMethod, fixedMethod) ;
取消延迟事件
[ self performSelector: @selector ( showMenu) withObject: nil afterDelay: 0.8f] ;
[ NSObject cancelPreviousPerformRequestsWithTarget: self selector: @selector ( showMenu) object: nil ] ;
解决UIImage比例失真的问题
UIImage * smallImage = [ image resizedImageWithContentMode: UIViewContentModeScaleAspectFit bounds: CGSizeMake( 640 , 960 ) interpolationQuality: kCGInterpolationDefault] ;
解决IOS4和IOS5背景的问题.
#if defined(__IPHONE_5_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_5_0
if ( [ self.navigationController.navigationBar respondsToSelector: @selector ( setBackgroundImage: forBarMetrics: ) ] ) {
[ self.navigationController.navigationBar setBackgroundImage: [ UIImage imageNamed: @ "TitleBar" ] forBarMetrics: UIBarMetricsDefault] ;
}
#endif
完美解决IOS4和IOS5背景问题.
UINavigationBar * _bar = self.navigationController.navigationBar;
// Insert ImageView
UIImage * _img = [ UIImage imageNamed: @ "best.png" ] ;
UIImageView * _imgv = [ [ [ UIImageView alloc] initWithImage: _img] autorelease] ;
_imgv.frame = _bar.bounds;
UIView * v = [ [ _bar subviews] objectAtIndex: 0 ] ;
v.layer.zPosition = - FLT_MAX ;
_imgv.layer.zPosition = - FLT_MAX + 1 ;
[ _bar insertSubview: _imgv atIndex: 1 ] ;
解决版本几版本编译问题.
if ( [ [ [ UIDevice currentDevice] systemVersion] floatValue] >= 5.0 ) {
#if defined(__IPHONE_5_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_5_0
[ self.navigationController.navigationBar setBackgroundImage: [ UIImage imageNamed: @ "preGPSImage.jpg" ] forBarMetrics: UIBarMetricsDefault] ;
#endif
}
else {
}
是否是中文字符
- ( BOOL ) isChineseStringFormat
{
NSPredicate * predicate = [ NSPredicate predicateWithFormat:
@ "SELF MATCHES %@" , @ "[\u 4e00-\u 9fa5]" ] ;
return [ predicate evaluateWithObject: self] ;
}