iOS开发:小技巧积累

来源:互联网 发布:html链接js不管用 编辑:程序博客网 时间:2024/05/16 07:42
1、获取全局的Delegate对象,这样我们可以调用这个对象里的方法和变量: 
Java代码  收藏代码
  1. [(MyAppDelegate*)[[UIApplication sharedApplication] delegate] MyMethodOrMyVariable];  


2、获得程序的主Bundle: 
Java代码  收藏代码
  1. NSBundle *bundle = [NSBundle mainBundle];  


Bundle可以理解成一种文件夹,其内容遵循特定的框架。 

Main Bundle一种主要用途是使用程序中的资源文件,如图片、声音、plst文件等。 
Java代码  收藏代码
  1. NSURL *plistURL = [bundle URLForResource:@"plistFile" withExtension:@"plist"];  

上面的代码获得plistFile.plist文件的路径。 

3、在程序中播放声音: 

首先在程序添加AudioToolbox: 
 
 
其次,在有播放声音方法的.m方法添加#import: 
Java代码  收藏代码
  1. #import<AudioToolbox/AudioToolbox.h>  

接下来,播放声音的代码如下: 
Java代码  收藏代码
  1. NSString *path = [[NSBundle mainBundle] pathForResource:@"soundFileName" ofType:@"wav"];   
  2. SystemSoundID soundID;   
  3. AudioServicesCreateSystemSoundID ((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);   
  4. AudioServicesPlaySystemSound (soundID);  


4、设置和获取类中属性值: 
Java代码  收藏代码
  1. [self setValue: 变量值 forKey: 变量名];  
  2. [self valueForKey: 变量名];  


5、让某一方法在未来某段时间之后执行: 
Java代码  收藏代码
  1. [self performSelector:@selector(方法名) withObject:nil afterDelay:延迟时间(s)];  


6、获得设备版本号: 
Java代码  收藏代码
  1. float version = [[[UIDevice currentDevice] systemVersion] floatValue];  


7、捕捉程序关闭或者进入后台事件: 
Java代码  收藏代码
  1. UIApplication *app = [UIApplication sharedApplication];  
  2. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];  

applicationWillResignActive:这个方法中添加想要的操作 

8、查看设备支持的字体: 
Java代码  收藏代码
  1. for (NSString *family in [UIFont familyNames]) {  
  2.     NSLog(@"%@", family);  
  3.     for (NSString *font in [UIFont fontNamesForFamilyName:family]) {  
  4.         NSLog(@"\t%@", font);  
  5.     }  
  6. }  


9、为UIImageView添加单击事件: 
Java代码  收藏代码
  1. imageView.userInteractionEnabled = YES;  
  2. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(yourHandlingCode:)];  
  3. [imageView addGestureRecognizer:singleTap]; 
原创粉丝点击