---
title: "IOS学习笔记"
author: "wenqxin"
date: "2013-07-18T23:15:25Z"
tags: []
categories: ["移动开发"]
slug: "ios"
draft: false
lastmod: "2013-07-18T23:15:25Z"
id: 1909924
url: "https://sectioncc.iteye.com/blog/1909924"
---

**1、UISearchBar自定义背景、取消按钮中文设置**

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

01. UISearchBar \*seachBar=\[\[UISearchBar alloc] init];
02. //修改搜索框背景
03. seachBar.backgroundColor=\[UIColor clearColor];
04. //去掉搜索框背景
05. \[\[searchbar.subviews objectAtIndex:0]removeFromSuperview];
06. for (UIView \*subview in seachBar.subviews)
07. {
08. if (\[subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
09. {
10. \[subview removeFromSuperview];
11. break;
12. }
13. }
14. //自定义背景
15. UIImageView \*imageView = \[\[UIImageView alloc] initWithImage:\[UIImage imageNamed:@"40-di.png"]];
16. \[searchBar insertSubview:imageView atIndex:1];
17. //输入搜索文字时隐藏搜索按钮，清空时显示
18. - (BOOL)searchBarShouldBeginEditing:(UISearchBar \*)searchBar {
19. searchBar.showsScopeBar = YES;
20. \[searchBar sizeToFit];
21. \[searchBar setShowsCancelButton:YES animated:YES];
22. return YES;
23. }
24. - (BOOL)searchBarShouldEndEditing:(UISearchBar \*)searchBar {
25. searchBar.showsScopeBar = NO;
26. \[searchBar sizeToFit];
27. \[searchBar setShowsCancelButton:NO animated:YES];
28. return YES;
29. }
30. //修改UISearchBar取消按钮中文字体
31. for (id aa in \[searchBar subviews]) {
32. if (\[aa isKindOfClass:\[UIButton class]]) {
33. UIButton \*btn = (UIButton \*)aa;
34. \[btn setTitle:@"取消" forState:UIControlStateNormal];
35. }
36. }

 

**2、UISearchBar**

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

01. #pragma mark 搜索控件
02. //搜索
03. - (void)searchBarSearchButtonClicked:(UISearchBar \*)searchBar{
04. UIStoryboard \*mainStory = \[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
05. FirstViewController \*fVC = \[mainStory instantiateViewControllerWithIdentifier:@"goFirstView"];
06. fVC.showStr = self.searchBar.text;
07. \[self presentModalViewController:fVC animated:YES];
08. }
09. //搜索输入内容时触发
10. - (void) searchBar:(UISearchBar \*)searchBar textDidChange:(NSString \*)searchText{
11. }
12. //焦点进入搜索
13. - (void) searchBarTextDidBeginEditing:(UISearchBar \*)searchBar{
14. self.soundBtn.hidden = YES;
15. \[self searchBar:searchBar activate:YES];
16. }
17. //取消搜索按钮
18. - (void) searchBarCancelButtonClicked:(UISearchBar \*)searchBar {
19. self.searchBar.text = @"";
20. self.soundBtn.hidden = NO;
21. \[self searchBar:searchBar activate:NO];
22. }
23. - (void)searchBar:(UISearchBar \*)searchBar activate:(BOOL) active{
24. if (!active) {
25. \[self.searchBar resignFirstResponder];
26. }
27. \[self.searchBar setShowsCancelButton:active animated:YES];
28. //修改UISearchBar取消按钮字体
29. for (id aa in \[searchBar subviews]) {
30. if (\[aa isKindOfClass:\[UIButton class]]) {
31. UIButton \*btn = (UIButton \*)aa;
32. \[btn setTitle:@"取消" forState:UIControlStateNormal];
33. }
34. }
35. }

 

**3、NSNotificationCenter通告中心**

   NSNotificationCenter通告与一个按钮中用addTarget绑定方法有些相似，按钮中的绑定触发事件时才调用关联消息。而NSNotificationCenter的范围则大得多，比如说摇动中，当触发摇动事件时，就提交并触发消息。

示例如下：

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

01. //1、需触发的消息方法
02. - (void) testNotification{
03. NSLog(@"测试通告中心。。。。。。。");
04. }
05. - (void)viewDidLoad
06. {
07. \[super viewDidLoad];
08. //2、对象注册，关联消息
09. \[\[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(testNotification) name:@"Dwen\_Notification" object:nil];
10. }
11. #pragma 通告中心
12. - (IBAction)notificationTest:(id)sender {
13. //3、提交消息
14. \[\[NSNotificationCenter defaultCenter] postNotificationName:@"Dwen\_Notification" object:@"Request Object"];
15. }

 

**4、视图显示和消失将会调用的方法，可处理一些前一界面的还原初始状态。**

\- (void) viewWillDisappear:  视图消失时调用

\- (void) viewWillAppear:      进入视图时调用

例如：点击搜索后，会的取消按钮，跳到下一界面再返回时，需把取消按钮隐藏掉可通过它们处理。

 

**5、获取程序的AppDelegate**

AppDelegate* appDelegate = (AppDelegate\*)\[\[UIApplication sharedApplication] delegate];

 

**6、ios4跳转界面**

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

1. QuotaManageViewController \*qmvc = \[\[QuotaManageViewController alloc] init];
2. \[self.navigationController pushViewController:qmvc animated:YES];
3. \[qmvc release];

 

**7、UILable换行**

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

1. lab\_1.lineBreakMode = UILineBreakModeWordWrap;
2. lab\_1.numberOfLines = 0;

 

**8、ipad中设置tableview背景无效，有两种解决方法：**

方法一：

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

1. UIView \*view = \[\[UIView alloc] init];
2. view.backgroundColor = \[UIColor clearColor];
3. tableView2.backgroundView = view;

 方法二：

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

1. if (\[self.tableView2 respondsToSelector:@selector(backgroundView)]) {
2. self.tableView2.backgroundView = nil;
3. }

 

**9、自定义UIView时，会继承它，下面是如何加载UIView对应xib。**

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

1. UIView \*head\_View = \[\[\[NSBundle mainBundle] loadNibNamed:@"HeadView" owner:self options:nil] lastObject];
2. head\_View.frame = CGRectMake(0, -120, self.view.frame.size.width, 150);
3. head\_View.backgroundColor = \[UIColor brownColor];
4. \[self.view addSubview:head\_View];

 

**10、对UIView进行旋转。2012-11-07**

今天在做ipad时，弹出的pop视图，总是横屏放着，不能竖屏。纠结了些时间，后来通过修改视图的坐标解决了该问题。

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

1. CGAffineTransform at = CGAffineTransformMakeRotation(M\_PI/2);//顺时钟旋转90
2. at = CGAffineTransformTranslate(at, 200, 0);
3. \[popVC.view setTransform:at];

 

**11、关于在UIView上进行滑动手势和点击事件手势。**

 

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

1. ///////////注flowView为UIView//////////
2. //添加滑动手势事件
3. UIPanGestureRecognizer \*gestureRecognizer = \[\[UIPanGestureRecognizer alloc] initWithTarget:flowView action:@selector(handleGesture:)];
4. \[flowView addGestureRecognizer:gestureRecognizer];
5. //添加点击手势事件
6. flowView.userInteractionEnabled = YES;
7. UITapGestureRecognizer \*tap = \[\[UITapGestureRecognizer alloc] initWithTarget:flowView action:@selector(goBigImageView)];
8. \[flowView addGestureRecognizer:tap];

 

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

01. //滑动手势（里面有手势的不同状态，根据需要进行灵活运用）
02. - (void)handleGesture:(UIPanGestureRecognizer \*)recognizer {
03. //UITapGestureRecognizer
04. if (recognizer.state == UIGestureRecognizerStateChanged){
05. NSLog(@"UIGestureRecognizerStateChanged");
06. }else if(recognizer.state == UIGestureRecognizerStateEnded){
07. NSLog(@"UIGestureRecognizerStateEnded");
08. }else if(recognizer.state == UIGestureRecognizerStateBegan){
09. NSLog(@"UIGestureRecognizerStateBegan");
10. }else if(recognizer.state == UIGestureRecognizerStateCancelled){
11. NSLog(@"UIGestureRecognizerStateCancelled");
12. }else if(recognizer.state == UIGestureRecognizerStateFailed){
13. NSLog(@"UIGestureRecognizerStateFailed");
14. }else if(recognizer.state == UIGestureRecognizerStatePossible){
15. NSLog(@"UIGestureRecognizerStatePossible");
16. }else if(recognizer.state == UIGestureRecognizerStateRecognized){
17. NSLog(@"UIGestureRecognizerStateRecognized");
18. }
19. }

 

**12、启动时异常**

Couldn't register com.yourcompany.ReciteWords with the bootstrap server. Error: unknown error code.  
This generally means that another instance of this process was already running or is hung in the debugger

解决方法，重启设备或模拟器

 

**13、读写plist文件**

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

01. - (void)readWritePlist{
02. //获取路径
03. NSString \*homePath = \[\[NSBundle mainBundle] executablePath];
04. NSArray \*strings = \[homePath componentsSeparatedByString: @"/"];
05. NSString \*executableName  = \[strings objectAtIndex:\[strings count]-1];
06. NSString \*baseDirectory = [homePath substringToIndex:
07. \[homePath length]-\[executableName length]-1];
08. //data.plist文件
09. NSString \*filePath = \[NSString stringWithFormat:@"%@/data.plist",baseDirectory];
10. NSLog(@"filePath: %@",filePath);
11. NSMutableDictionary \*dataDict = \[\[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
12. NSLog(@"dataDict: %@",dataDict);
13. //change the value or add the value
14. \[dataDict setObject:@"YES" forKey:@"Trial"];
15. \[dataDict setValue:@"dwen" forKey:@"nickName"];
16. //write back to data.plist file
17. \[dataDict writeToFile:filePath atomically:NO];
18. }

 

**14、ios生成随机数(三种方式)：**

 int i = rand() % 5;

int i = random() % 5;

int  x = arc4random() % 100;//\[0,100] 包括0 ，不包括100

int  y = (arc4random() % 501) + 500;//\[500,1000 ]，包括500 ，不包括1000

 

**15、UIImage图片处理：缩放、设定大小、存储 (转载)**

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

01. //1.等比率缩放
02. - (UIImage \*)scaleImage:(UIImage \*)image toScale:(float)scaleSize{
03. UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize);
04. \[image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
05. UIImage \*scaledImage = UIGraphicsGetImageFromCurrentImageContext();
06. UIGraphicsEndImageContext();
07. return scaledImage;
08. }
09. //2.自定长宽
10. - (UIImage \*)reSizeImage:(UIImage \*)image toSize:(CGSize)reSize{
11. UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height));
12. \[image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
13. UIImage \*reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
14. UIGraphicsEndImageContext();
15. return reSizeImage;
16. }
17. //3.处理某个特定View
18. 只要是继承UIView的object 都可以处理
19. 必须先import QuzrtzCore.framework
20. -(UIImage\*)captureView:(UIView \*)theView{
21. CGRect rect = theView.frame;
22. UIGraphicsBeginImageContext(rect.size);
23. CGContextRef context = UIGraphicsGetCurrentContext();
24. \[theView.layer renderInContext:context];
25. UIImage \*img = UIGraphicsGetImageFromCurrentImageContext();
26. UIGraphicsEndImageContext();
27. return img;
28. }
29. //4.储存图片
30. 储存图片这里分成储存到app的文件里, 储存到手机的图片库里
31. // 储存到app的文件里
32. NSString \*path = \[\[NSHomeDirectory()stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:@"image.png"];
33. \[UIImagePNGRepresentation(image) writeToFile:pathatomically:YES];

 

**16、object-c正则验证，方式之一，如下：**

    **NSPredicate用于指定过滤器的条件。通过该对象准确地描述所需条件，对每个对象通过谓词进行筛选，判断它们是否与条件相匹配。**

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

1. NSString \*numberRegex = @"\[1-4]";
2. NSPredicate \*number = \[NSPredicate predicateWithFormat:@"SELF MATCHES %@",numberRegex];
3. bool result = \[number evaluateWithObject:@"1"];

 

 

**17、定义程序块**

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

1. //定义程序块
2. void(^loggerBlock)(void);
3. //实现程序块
4. loggerBlock = ^{NSLog(@"i am test block.");};
5. //执行程序块
6. loggerBlock();

 

**18、反射**

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

1. //反射(对CodingVo类进行反射)
2. Class cls = NSClassFromString(@"CodingVo");
3. id obj = \[\[cls alloc] init];
4. SEL selector = NSSelectorFromString(@"test1");
5. //调用CodingVo类中test1方法
6. \[obj performSelector:selector withObject:nil];

 

**19、调用短信、电话、邮件、Safari浏览器API**

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

01. //调用短信
02. - (IBAction)callMsg:(id)sender {
03. \[\[UIApplication sharedApplication] openURL:\[NSURL URLWithString:@"sms://135587"]];
04. }
05. //调用电话
06. - (IBAction)callTel:(id)sender {
07. \[\[UIApplication sharedApplication] openURL:\[NSURL URLWithString:@"tel://135587"]];
08. }
09. //调用Safari浏览器
10. - (IBAction)callSafari:(id)sender {
11. \[\[UIApplication sharedApplication] openURL:\[NSURL URLWithString:@"http://www.baidu.com/"]];
12. }
13. // 调用email
14. - (IBAction)callEmail:(id)sender {
15. \[\[UIApplication sharedApplication] openURL:\[NSURL URLWithString:@"mailto://test@126.com"]];
16. }

 

**20、操作声音文件，添加AudioToolbox.framework库。**

#import &lt;AudioToolbox/AudioToolbox.h&gt;

@property (assign,nonatomic) SystemSoundID soundID;

//测试播放声音  
\- (void) testSound{  
    NSString \*path = \[\[NSBundle mainBundle] pathForResource:@"2" ofType:@"caf"];  
    NSURL \*url = \[NSURL fileURLWithPath:path];  
    AudioServicesCreateSystemSoundID((\_\_bridge CFURLRef)(url), &soundID);  
    AudioServicesPlaySystemSound(soundID);  
    NSLog(@"testSound...mp3音频文件格式不支持");  
}

 

**21、ios触摸事件监听和操作(UITouch)**

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

01. //手指触摸屏幕时报告
02. - (void)touchesBegan:(NSSet \*)touches withEvent:(UIEvent \*)event{
03. NSLog(@"touchesBegan");
04. }
05. //手指在屏幕上移动时报告
06. - (void)touchesMoved:(NSSet \*)touches withEvent:(UIEvent \*)event{
07. NSLog(@"touchesMoved");
08. }
09. //手指离开屏幕时报告
10. - (void)touchesEnded:(NSSet \*)touches withEvent:(UIEvent \*)event{
11. NSLog(@"touchesEnded");
12. }
13. //因接听电话或其他因素导致取消触摸时报告
14. - (void)touchesCancelled:(NSSet \*)touches withEvent:(UIEvent \*)event{
15. NSLog(@"touchesCancelled");
16. }

 

**22、\\u00B0表示角度符号**

NSString \*latitudeStr = \[NSString stringWithFormat:@"%g\\u00B0",newLocation.coordinate.latitude];  
![](http://dl.iteye.com/upload/attachment/0080/9094/fbc854b7-b1f0-36eb-a892-2f01ad43919f.png)  
 

 **23、实现ios动画效果有两种方式，一种是UIView层面上的,另一种是CATransation更底层次控制**

 

**24、设备信息**

NSLog(@"系统名称：%@ ,系统版本： %@",\[\[UIDevice currentDevice] systemName],\[\[UIDevice currentDevice] systemVersion]);

 

 **25、MPMoviePlayerViewController控件中，需把Done改为中文，对工程中plist文件进行设置。对其他英文控件中的英文文本也有同样有效。设置见下图：**

![](http://dl.iteye.com/upload/attachment/0081/0405/dd535ed0-927d-3406-b16d-04decd19eb81.png)  
 

 **26、文本层CATextLayer**

 

C代码  [![收藏代码](http://wenxin2009.iteye.com/images/icon_star.png)]()

1. CATextLayer \*txtLayer = \[CATextLayer layer];
2. txtLayer.string = @"地球";
3. txtLayer.foregroundColor = \[\[UIColor redColor] CGColor];
4. txtLayer.bounds = CGRectMake(0, 0, 200, 50);
5. txtLayer.position = CGPointMake(0, 0);
6. \[imageLayer addSublayer:txtLayer];

 

 **27、assign、retain、copy、readonly区别**

assign：指定setter方法用简单的赋值，这是默认操作。你可以对标量类型（如int）使用这个属性。你可以想象一个float，它不是一个对象，所以它不能retain、copy。

retain：指定retain应该在后面的对象上调用，前一个值发送一条release消息。你可以想象一个NSString实例，它是一个对象，而且你可能想要retain它。

copy：指定应该使用对象的副本（深度复制），前一个值发送一条release消息。基本上像retain，但是没有增加引用计数，是分配一块新的内存来放置它。

readonly：将只生成getter方法而不生成setter方法（getter方法没有get前缀）。

readwrite：默认属性，将生成不带额外参数的getter和setter方法（setter方法只有一个参数）。

atomic：对于对象的默认属性，就是setter/getter生成的方法是一个原子操作。如果有多个线程同时调用setter的话，不会出现某一个线程执行setter全部语句之前，另一个线程开始执行setter的情况，相关于方法头尾加了锁一样。

nonatomic：不保证setter/getter的原子性，多线程情况下数据可能会有问题

**28、声明关键字前加extern，为外部变量。外部变量可被其他任何方法或函数访问和更改其值的变量。**