iOS开发中 常用枚举和常用的一些运算符(易错总结)

1、色值的随机值:
[objc]  view plain  copy
  1. #define kColorValue arc4random_uniform(256)/255.0  
  2. //  arc4random_uniform(256)/255.0;  求出0.0~1.0之间的数字  
  3.     view.backgroundColor = [UIColor colorWithRed:kColorValue green: kColorValue blue: kColorValue alpha0.5];  

2、定时器的使用:
[objc]  view plain  copy
  1. [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(fromOutToInside) userInfo:nil repeats:YES];  

3、退回键盘触发方法
[objc]  view plain  copy
  1. - (BOOL)textFieldShouldReturn:(UITextField *)textField;{  
  2.     [textField resignFirstResponder];  
  3.     return YES;  
  4. }  

4、点击空白回收键盘
[objc]  view plain  copy
  1. - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{  
  2.  for (int i = 0; i < 5; i ++ ) {  
  3.         [field resignFirstResponder];  
  4. }  

5、UILabel切圆角,下面两个同时才能显示
    label.layer.cornerRadius = 10;//切圆角
    label.layer.masksToBounds = YES;
6、  UITextField文本框类型 (圆角)
    textField.borderStyle = UITextBorderStyleRoundedRect;
7、定时器
[objc]  view plain  copy
  1. [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(printHelloword) userInfo:nil repeats:YES];  

8、UITextField 文本框的叉号,X
[objc]  view plain  copy
  1. _field.clearButtonMode =  UITextFieldViewModeAlways;  


9、设置导航默认标题的颜色及字体大小  
[objc]  view plain  copy
  1. self.navigationController.navigationBar.titleTextAttributes = @{UITextAttributeTextColor: [UIColor whiteColor],    
  2.   UITextAttributeFont : [UIFont boldSystemFontOfSize:18]};   


11、身份证号处理
[objc]  view plain  copy
  1. - (NSString *)ittemDisposeIdcardNumber:(NSString *)idcardNumber {  
  2.     //星号字符串  
  3.     NSString *xinghaoStr = @"";  
  4.     //动态计算星号的个数  
  5.     for (int i  = 0; i < idcardNumber.length - 7; i++) {  
  6.         xinghaoStr = [xinghaoStr stringByAppendingString:@"*"];  
  7.     }  
  8.     //身份证号取前3后四中间以星号拼接  
  9.     idcardNumber = [NSString stringWithFormat:@"%@%@%@",[idcardNumber substringToIndex:3],xinghaoStr,[idcardNumber substringFromIndex:idcardNumber.length-4]];  
  10.     //返回处理好的身份证号  
  11.     return idcardNumber;  
  12. }  

----------------------------------------------------------------------------------------------------------
12、//调整字间距
 
[objc]  view plain  copy
  1. CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number;);  
  2.   [attributedString addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(0, [attributedString length])];  
  3.   //调整行间距  
  4.   [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [_messageLabel.text length])];  
  5.   _messageLabel.attributedText = attributedString;  

----------------------------------------------------------------------
13、ios8适配地图授权问题
iOS8修改了位置设置里的内容,增加了一套状态(使用中可用/通常可用),所以以前的CLLcationManage的注册后, 
Delegate接口不响应了。 
  iOS8需要这么设置 
第一步 
[objc]  view plain  copy
  1.     location = [[CLLocationManager alloc] init];   
  2. location.delegateself;   
  3. [locationrequestAlwaysAuthorization];   

第二步 
在Plist中追加下面两个字段 (必须有,最少一个,内容是系统ALert的文言,文言可为空) 
第三步 
有了新的Delegate方法。 
[objc]  view plain  copy
  1. - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status   
  2. switch (status) {   
  3. casekCLAuthorizationStatusNotDetermined:   
  4.             if ([location respondsToSelector:@selector(requestAlwaysAuthorization)]) {   
  5. [locationrequestAlwaysAuthorization];   
  6.             }   
  7.             break;   
  8.         default:   
  9.             break;     }   
  10. }  

----------------------------------------------------------------------
14、一段文字设置多种字体颜色
//设置不同字体颜色
[objc]  view plain  copy
  1. -(void)fuwenbenLabel:(UILabel *)labell FontNumber:(id)font AndRange:(NSRange)range AndColor:(UIColor *)vaColor  
  2. {  
  3.     NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:labell.text];  
  4.     //设置字号  
  5.     [str addAttribute:NSFontAttributeName value:font range:range];  
  6.     //设置文字颜色  
  7.     [str addAttribute:NSForegroundColorAttributeName value:vaColor range:range];  
  8.     labell.attributedText = str;  
  9. }  

----------------------------------------------------------------------
15、由身份证号码返回性别
[objc]  view plain  copy
  1. -(NSString *)sexStrFromIdentityCard:(NSString *)numberStr{  
  2.     NSString *result = nil;  
  3.   
  4.     BOOL isAllNumber = YES;  
  5.   
  6.     if([numberStr length]<17)  
  7.         return result;  
  8.   
  9.     //**截取第17为性别识别符  
  10.     NSString *fontNumer = [numberStr substringWithRange:NSMakeRange(161)];  
  11.   
  12.     //**检测是否是数字;  
  13.     const charchar *str = [fontNumer UTF8String];  
  14.     const charchar *p = str;  
  15.     while (*p!='\0') {  
  16.         if(!(*p>='0'&&*p<='9'))  
  17.             isAllNumber = NO;  
  18.         p++;  
  19.     }  
  20.     if(!isAllNumber)  
  21.         return result;  
  22.     int sexNumber = [fontNumer integerValue];  
  23.     if(sexNumber%2==1)  
  24.         result = @"男";  
  25.     ///result = @"M";  
  26.     else if (sexNumber%2==0)  
  27.         result = @"女";  
  28.     //result = @"F";  
  29.     return result;  
  30. }  

----------------------------------------------------------------------
16、iphone开发之获取系统字体
[objc]  view plain  copy
  1. + (NSArray*)getAllSystemFonts;  
  2. {  
  3.     NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];  
  4.     NSArray* familys = [UIFont familyNames];  
  5.   
  6.     for (id obj in familys) {  
  7.         NSArray* fonts = [UIFont fontNamesForFamilyName:obj];  
  8.         for (id font in fonts)       
  9.         {  
  10.             [array addObject:font];  
  11.         }  
  12.     }  
  13.     return array;   
  14. }  
  15. + (UIFont*)getCurrentFont  
  16. {  
  17.     //判断系统字体的size,返回使用的字体。  
  18.     UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]];  
  19.     return font;  
  20. }  

----------------------------------------------------------------------
17、输入字体,内容。自动算范围
内容:字符串,输入字体大小,和需要多宽
[objc]  view plain  copy
  1. CGSize size1 = [内容 sizeWithFont:[UIFont boldSystemFontOfSize:13] constrainedToSize:CGSizeMake(宽度, 10000)];  
  2. -(CGFloat)getHeight:(NSString *)text andWidth:(CGFloat)width andFont:(UIFont *)font  
  3. {  
  4.     CGRect frame =  [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil] ;  
  5.     return  frame.size.height ;  
  6. }  


18、#region 将Base64编码的文本转换成普通文本
[objc]  view plain  copy
  1. /// <summary>  
  2. /// 将Base64编码的文本转换成普通文本  
  3. /// </summary>  
  4. /// <param name="base64">Base64编码的文本</param>  
  5. /// <returns></returns>  
  6. public static string Base64StringToString(string base64)  
  7. {  
  8.     if (base64 != "")  
  9.     {  
  10.         char[] charBuffer = base64.ToCharArray();  
  11.         byte[] bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length);  
  12.         string returnstr = Encoding.Default.GetString(bytes);  
  13.         return returnstr;  
  14.     }  
  15.     else  
  16.     {  
  17.         return "";  
  18.     }  
  19. }  
  20. #endregion  
  21. #region 字符串转为base64字符串  
  22. public static string changebase64(string str)  
  23. {  
  24.     if (str != "" && str != null)  
  25.     {  
  26.         byte[] b = Encoding.Default.GetBytes(str);  
  27.         string returnstr = Convert.ToBase64String(b);  
  28.         return returnstr;  
  29.     }  
  30.     else  
  31.     {  
  32.         return "";  
  33.     }  
  34. }  
  35. #endregion  


19、获取文件路径
[objc]  view plain  copy
  1. NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Contacts.plist" ofType:nil];  

 20修改title的字体颜色
   
[objc]  view plain  copy
  1. NSDictionary *dic = @{NSForegroundColorAttributeName : [UIColor whiteColor]};  
  2.    self.navigationController.navigationBar.titleTextAttributes = dic;  


21、添加头像的方法
//调用添加手势的方法
[objc]  view plain  copy
  1. [self addTapGesture];  

//给aImageView 视图添加轻拍手势
[objc]  view plain  copy
  1. - (void)addTapGesture{  
  2.     UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap : )];  
  3.      
  4.     [self.aview.aImageView addGestureRecognizer:tap];  
  5.     [tap release];  
  6.      
  7. }  


//实现轻拍手势的方法
[objc]  view plain  copy
  1. - (void)handleTap : (UITapGestureRecognizer *)tap{  
  2. //添加ActionSheet控件 提示选项框  
  3.     UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从手机中选择", nil nil];  
  4.     //在当前界面显示actionSheet对象  
  5.     [actionSheet showInView:self.view];  
  6.     [actionSheet release];  
  7. }  



[objc]  view plain  copy
  1. - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{  
  2.     switch (buttonIndex) {  
  3.         case 0:  
  4.             //拍照  
  5.             NSLog(@"拍照");  
  6.             [self pickerPictureFromCamera];  
  7.             break;  
  8.             case 1:  
  9.             //从相册中读取照片  
  10.             NSLog(@"从相册中读取照片");  
  11.             [self pickerPictureFormPhotoAlbum];  
  12.             break;  
  13.         default:  
  14.             break;  
  15.     }  
  16.      
  17. }  


//拍照
[objc]  view plain  copy
  1. - (void)pickerPictureFromCamera{  
  2.     //判断前摄像头是否可以使用  
  3. BOOL isCameera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];  
  4. //    UIImagePickerControllerCameraDeviceFront   前摄像头  
  5. //    UIImagePickerControllerCameraDeviceRear  //后摄像头  
  6.     if (!isCameera) {  
  7.         NSLog(@"没有摄像头可以使用");  
  8.         return;  
  9.     }  
  10.     //初始化图片选择控制器对象  
  11.     UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];  
  12.     //设置图片选择器选取图片的样式  
  13.     imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;  
  14.     //设置取出来的图片是否允许编辑  
  15.     imagePicker.allowsEditing = YES;  
  16.     //设置代理  
  17.     imagePicker.delegate = self;  
  18.     //把手机相机推出来  
  19.     [self presentViewController:imagePicker animated:YES completion:nil];  
  20.     [imagePicker release];  
  21.      
  22. }  


//从相册中取出相片
[objc]  view plain  copy
  1. - (void)pickerPictureFormPhotoAlbum{  
  2.     UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];  
  3.     //设置图片格式  
  4.     imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;  
  5.     //设置允许编辑  
  6.     imagePicker.allowsEditing = YES;  
  7.     //设置代理  
  8.     imagePicker.delegate = self;  
  9.      
  10.     [self presentViewController:imagePicker animated:YES completion:nil];  
  11.     [imagePicker release];  
  12.      
  13. }  


[objc]  view plain  copy
  1. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{  
  2.     //从字典中取出编辑的key值,对应的照片  
  3.     self.aview.aImageView.image = [info objectForKey:UIImagePickerControllerEditedImage];  
  4.     //自己推出来的自己收回去  
  5.     [self dismissViewControllerAnimated:YES completion:nil];  
  6. }  

================================================================================
22.NSUserDefaults适合存储轻量级的本地数据,比如要保存一个登陆界面的数据,用户名、密码之类的,个人觉得使用NSUserDefaults是首选。下次再登陆的时候就可以直接从NSUserDefaults里面读取上次登陆的信息咯。

因为如果使用自己建立的plist文件什么的,还得自己显示创建文件,读取文件,很麻烦,而是用NSUserDefaults则不用管这些东西,就像读字符串一样,直接读取就可以了。

NSUserDefaults支持的数据格式有:NSNumber(Integer、Float、Double),NSString,NSDate,NSArray,NSDictionary,BOOL类型
23.封装一个解析的方法:
//封装一个解析的方法
[objc]  view plain  copy
  1. - (void)parserData : (NSData *)data{  
  2.     //解析:  
  3.     NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];  
  4.     //    NSLog(@"%@",dataDic); 验证!  
  5.     //取出results key值对应的数组  
  6.     NSArray *array = dataDic[@"results"];  
  7.     //遍历数组的字典,并使用给Business对象赋值  
  8.     for (NSDictionary *dic in array) {  
  9.         //创建数据模型对象  
  10.         Business *bus = [[Business alloc]init];  
  11.          
  12.         //使用kvc给bus赋值  
  13.         [bus setValuesForKeysWithDictionary:dic];  
  14.          
  15.         //添加到存储所有商户信息的数组  
  16.         [self.dataSource addObject:bus];  
  17.         //释放  
  18.         [bus release];  
  19.         //        NSLog(@"%@",self.dataSource); 验证!   
  20.     }  
  21.     //刷新ui界面  
  22.     [self.tableView reloadData];  
  23. }  



24、  '-[Person encodeWithCoder:]: unrecognized selector sent to instance 0x7fc831d9c880   方法没实现
25、计算字符串的大小:
[objc]  view plain  copy
  1. + (CGSize)getStringSize:(NSString *)text strMaxWidth:(CGFloat )width fontSize:(UIFont *)fontSize{  
  2.     CGSize constraint = CGSizeMake(width, MAXFLOAT);  
  3.     NSDictionary *dict = [NSDictionary dictionaryWithObject:fontSize forKey: NSFontAttributeName];  
  4.     CGSize size = CGSizeZero;  
  5.     if (isAboveIOS7) {  
  6.         size = [text boundingRectWithSize:constraint  
  7.                                   options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading  
  8.                                attributes:dict  
  9.                                   context:nil].size;  
  10.         return size;  
  11.     }  
  12.     size = [text sizeWithFont:fontSize  
  13.             constrainedToSize:constraint  
  14.                 lineBreakMode:NSLineBreakByWordWrapping];  
  15.   
  16.     return size;  
  17. }  

26、storyboard传值:
[objc]  view plain  copy
  1. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {  
  2.      
  3.     //获取segue起始端的视图控制器对象  
  4.    RootViewController *rootVC =  [segue sourceViewController];  
  5.      
  6. //通过segue完成跳转的时候会触发这个方法,在跳转之前触发,一般用来传值  
  7.     //获取push过去后的视图控制器对象  
  8.     DetailViewController *detailVC = [segue destinationViewController];  
  9.     //把textField中的内容取出来赋值给下一个界面的属性  
  10.     detailVC.string = rootVC.textField.text;// rootVC.textField.text 相当于 self.textField.text  
  11. }  


27.赋值方法中基本数据类型转字符串
 
[objc]  view plain  copy
  1. self.ageLabel.text = [NSString stringWithFormat:@"%ld",person.age];  

28.UIViewController中关于nib初始化的函数

[objc]  view plain  copy
  1. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;  

从这个函数的说明我们可以知道,如果你subclass一个UIViewController,不管有没有使用NIB, [super initWithNibName:bundle]这个方法必须被调用, 这个方法会在如下两种情况下被调用:

  • 显示调用, 指定一个nib名称,系统会去找指定的nib
  • 在父类的Init方法中被调用,如果这种情况,两个参数都会是nil,系统会去找和你自定以的UIViewController相同名字的nib
如果系统找到nib文件,就会把nib文件中的内容加载进来, 有一点需要解释,initWithNibName:bundle方法并不会加载nib, 当UIViewController的view属性第一次被使用的时候,系统就会调用UIViewController中的loadView方法,在这个方法中会加载nib文件。
如果不用nib,我们可以在loadview中创建view的层次结构,对于有nib的情况,我们也可以在这个方法中做想要的修改。

NSBundle Nib装载方法

Resource programming guide 文档详细介绍了nib的装载过程,例如可以用loadNibNamed:owner方法,但是这个方法只是做了loadNib的事情。

29、解决webView的汉字显示问题
[objc]  view plain  copy
  1. NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://linode-back-cn.b0.upaiyun.com/articles/d34/372/db6edd24d68302930fbc5fd44c.html"]]];  
  2.       [self.webView loadData:data MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:nil];  


30.IOS 登陆注销功能的实现

1、在appDelegate中加入一个navigation用来控制所有的页面跳转
2、将login页面作为navigation的root view
3、在appDelegate中判断程序是否是第一次登陆,如果是直接进入login页面,如果不是则跳过login页面,push下一个页面(程序主页面,且采用的是tab+nav的结构)
4、程序主页面中对应的每个tab页面都是一个nav的结构
5、当点击注销按钮时,利用appDelegate中的导航将主页面pop出来,此时程序便又重新回到了login页面。

31.Label自适应高度

[objc]  view plain  copy
  1. UILabel *descLable=[[UILabel alloc] init];  
  2.     [descLable setNumberOfLines:0];  
  3.     descLable.lineBreakMode = UILineBreakModeCharacterWrap;  
  4.     descLable.text = _newsListModel.news_comtent;  
  5.     descLable.font = [UIFont systemFontOfSize:12];  
  6.     UIFont *font = [UIFont fontWithName:@"Arial" size:12];  
  7.     CGSize size = CGSizeMake(300, MAXFLOAT);  
  8.     CGSize labelsize = [_newsListModel.news_comtent sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeCharacterWrap];  
  9.     [descLable setFrame:CGRectMake(10280,300, labelsize.height)];  
  10.     [headView addSubview:descLable];  
  11.   
  12.   
  13. view.backgourd.color = [uicolor  colorwithred green blue alpha:0.5]  

————————————————————————————————————————————————————————————————————————
32、SDWebImage手动清除缓存的方法

1.找到SDImageCache类

2.添加如下方法:

[objc]  view plain copy
  1. - (float)checkTmpSize  
  2. {  
  3.     float totalSize = 0;  
  4.     NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:diskCachePath];  
  5.     for (NSString *fileName in fileEnumerator)  
  6.     {  
  7.         NSString *filePath = [diskCachePath stringByAppendingPathComponent:fileName];  
  8.   
  9.         NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];  
  10.   
  11.         unsigned long long length = [attrs fileSize];  
  12.   
  13.         totalSize += length / 1024.0 / 1024.0;  
  14.     }  
  15. //    NSLog(@"tmp size is %.2f",totalSize);  
  16.   
  17.     return totalSize;  
  18. }  


新版的SDImageCache类,已增加此方法

[objc]  view plain copy
  1. [[SDImageCache sharedImageCache] getSize];  
3.在设置里这样使用

[objc]  view plain copy
  1. #pragma 清理缓存图片  
  2.   
  3. - (void)clearTmpPics  
  4. {  
  5.     [[SDImageCache sharedImageCache] clearDisk];  
  6.   
  7. //    [[SDImageCache sharedImageCache] clearMemory];//可有可无  
  8.   
  9.     DLog(@"clear disk");      
  10.   
  11.     float tmpSize = [[SDImageCache sharedImageCache] checkTmpSize];  
  12.   
  13.     NSString *clearCacheName = tmpSize >= 1 ? [NSString stringWithFormat:@"清理缓存(%.2fM)",tmpSize] : [NSString stringWithFormat:@"清理缓存(%.2fK)",tmpSize * 1024];  
  14.   
  15.     [configDataArray replaceObjectAtIndex:2 withObject:clearCacheName];  
  16.   
  17.     [configTableView reloadData];  
  18. }  

32、第三方MJ使用方法
1、只需修改环境中的footer和base   -fobjc-arc

2、选中项目 - Project - Build Settings - ENABLE_STRICT_OBJC_MSGSEND  将其设置为 NO 即可


常用和易错的记录会持续更新..............敬请关注!
转自  http://blog.csdn.net/qq_31810357/article/details/49404345
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值