iOS開發(fā)之小技巧積累
1、獲取全局的Delegate對象,這樣我們可以調(diào)用這個對象里的方法和變量:
- [(MyAppDelegate*)[[UIApplication sharedApplication] delegate] MyMethodOrMyVariable];
2、獲得程序的主Bundle:
- NSBundle *bundle = [NSBundle mainBundle];
Bundle可以理解成一種文件夾,其內(nèi)容遵循特定的框架。
Main Bundle一種主要用途是使用程序中的資源文件,如圖片、聲音、plst文件等。
- NSURL *plistURL = [bundle URLForResource:@"plistFile" withExtension:@"plist"];
上面的代碼獲得plistFile.plist文件的路徑。
3、在程序中播放聲音:
首先在程序添加AudioToolbox:
其次,在有播放聲音方法的.m方法添加#import:
- #import<AudioToolbox/AudioToolbox.h>
接下來,播放聲音的代碼如下:
- NSString *path = [[NSBundle mainBundle] pathForResource:@"soundFileName" ofType:@"wav"];
- SystemSoundID soundID;
- AudioServicesCreateSystemSoundID ((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
- AudioServicesPlaySystemSound (soundID);
4、設(shè)置和獲取類中屬性值:
- [self setValue: 變量值 forKey: 變量名];
- [self valueForKey: 變量名];
5、讓某一方法在未來某段時間之后執(zhí)行:
- [self performSelector:@selector(方法名) withObject:nil afterDelay:延遲時間(s)];
6、獲得設(shè)備版本號:
- float version = [[[UIDevice currentDevice] systemVersion] floatValue];
7、捕捉程序關(guān)閉或者進入后臺事件:
- UIApplication *app = [UIApplication sharedApplication];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
applicationWillResignActive:這個方法中添加想要的操作
8、查看設(shè)備支持的字體:
- for (NSString *family in [UIFont familyNames]) {
- NSLog(@"%@", family);
- for (NSString *font in [UIFont fontNamesForFamilyName:family]) {
- NSLog(@"\t%@", font);
- }
- }
9、為UIImageView添加單擊事件:
- imageView.userInteractionEnabled = YES;
- UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(yourHandlingCode:)];
- [imageView addGestureRecognizer:singleTap];
10、添加多語言支持:
比如Image Picker這樣的組件,它上面的按鈕的文字是隨著設(shè)備語言環(huán)境的改變而改變的,但是要先在工程添加語言:
11、使程序支持iTunes這樣的設(shè)備,比如可以使用PC端的工具往程序的Documents中拖放文件:
12、頁面切換效果設(shè)置:
- controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
- [self presentModalViewController:controller animated:YES];
可供使用的效果:
- UIModalTransitionStyleCoverVertical //新視圖從下向上出現(xiàn)
- UIModalTransitionStyleFlipHorizontal //以設(shè)備的長軸為中心翻轉(zhuǎn)出現(xiàn)
- UIModalTransitionStyleCrossDissolve //漸漸顯示
- UIModalTransitionStylePartialCurl //原視圖向上卷起
恢復(fù)之前的頁面:
- [self dismissModalViewControllerAnimated:YES];
13、獲取截屏
- - (UIImage *)getScreenShot {
- UIGraphicsBeginImageContext(self.view.bounds.size);
- [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
- UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
- return image;
- }