1、色值的随机值:
#define kColorValue arc4random_uniform(256)/255.0 // arc4random_uniform(256)/255.0; 求出0.0~1.0之间的数字 view.backgroundColor = [UIColor colorWithRed:kColorValue green: kColorValue blue: kColorValue alpha: 0.5];
2、定时器的使用:
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(fromOutToInside) userInfo:nil repeats:YES];
3、退回键盘触发方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField;{ [textField resignFirstResponder]; return YES; }
4、点击空白回收键盘
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ for (int i = 0; i < 5; i ++ ) { [field resignFirstResponder]; }
5、UILabel切圆角,下面两个同时才能显示
label.layer.cornerRadius
=
10;//切圆角
label.layer.masksToBounds = YES;
6、 UITextField文本框类型
(圆角)
(圆角)
textField.borderStyle
=
UITextBorderStyleRoundedRect;
=
UITextBorderStyleRoundedRect;
7、定时器
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(printHelloword) userInfo:nil repeats:YES];
8、UITextField 文本框的叉号,X
_field.clearButtonMode = UITextFieldViewModeAlways;
9、设置导航默认标题的颜色及字体大小
self.navigationController.navigationBar.titleTextAttributes = @{UITextAttributeTextColor: [UIColor whiteColor], UITextAttributeFont : [UIFont boldSystemFontOfSize:18]};
11、身份证号处理
- (NSString *)ittemDisposeIdcardNumber:(NSString *)idcardNumber { //星号字符串 NSString *xinghaoStr = @""; //动态计算星号的个数 for (int i = 0; i < idcardNumber.length - 7; i++) { xinghaoStr = [xinghaoStr stringByAppendingString:@"*"]; } //身份证号取前3后四中间以星号拼接 idcardNumber = [NSString stringWithFormat:@"%@%@%@",[idcardNumber substringToIndex:3],xinghaoStr,[idcardNumber substringFromIndex:idcardNumber.length-4]]; //返回处理好的身份证号 return idcardNumber; }
----------------------------------------------------------------------------------------------------------
12、//调整字间距
CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number;); [attributedString addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(0, [attributedString length])]; //调整行间距 [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [_messageLabel.text length])]; _messageLabel.attributedText = attributedString;
----------------------------------------------------------------------
13、ios8适配地图授权问题
iOS8修改了位置设置里的内容,增加了一套状态(使用中可用/通常可用),所以以前的CLLcationManage的注册后,
Delegate接口不响应了。
iOS8需要这么设置
第一步
location = [[CLLocationManager alloc] init]; location.delegate= self; [locationrequestAlwaysAuthorization];
第二步
在Plist中追加下面两个字段 (必须有,最少一个,内容是系统ALert的文言,文言可为空)
第三步
有了新的Delegate方法。
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { switch (status) { casekCLAuthorizationStatusNotDetermined: if ([location respondsToSelector:@selector(requestAlwaysAuthorization)]) { [locationrequestAlwaysAuthorization]; } break; default: break; } }
----------------------------------------------------------------------
14、一段文字设置多种字体颜色
//设置不同字体颜色
-(void)fuwenbenLabel:(UILabel *)labell FontNumber:(id)font AndRange:(NSRange)range AndColor:(UIColor *)vaColor { NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:labell.text]; //设置字号 [str addAttribute:NSFontAttributeName value:font range:range]; //设置文字颜色 [str addAttribute:NSForegroundColorAttributeName value:vaColor range:range]; labell.attributedText = str; }
----------------------------------------------------------------------
15、由身份证号码返回性别
-(NSString *)sexStrFromIdentityCard:(NSString *)numberStr{ NSString *result = nil; BOOL isAllNumber = YES; if([numberStr length]<17) return result; //**截取第17为性别识别符 NSString *fontNumer = [numberStr substringWithRange:NSMakeRange(16, 1)]; //**检测是否是数字; const char *str = [fontNumer UTF8String]; const char *p = str; while (*p!='\0') { if(!(*p>='0'&&*p<='9')) isAllNumber = NO; p++; } if(!isAllNumber) return result; int sexNumber = [fontNumer integerValue]; if(sexNumber%2==1) result = @"男"; ///result = @"M"; else if (sexNumber%2==0) result = @"女"; //result = @"F"; return result; }
----------------------------------------------------------------------
16、iphone开发之获取系统字体
+ (NSArray*)getAllSystemFonts; { NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease]; NSArray* familys = [UIFont familyNames]; for (id obj in familys) { NSArray* fonts = [UIFont fontNamesForFamilyName:obj]; for (id font in fonts) { [array addObject:font]; } } return array; } + (UIFont*)getCurrentFont { //判断系统字体的size,返回使用的字体。 UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]]; return font; }
----------------------------------------------------------------------
17、输入字体,内容。自动算范围
内容:字符串,输入字体大小,和需要多宽
CGSize size1 = [内容 sizeWithFont:[UIFont boldSystemFontOfSize:13] constrainedToSize:CGSizeMake(宽度, 10000)]; -(CGFloat)getHeight:(NSString *)text andWidth:(CGFloat)width andFont:(UIFont *)font { CGRect frame = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil] ; return frame.size.height ; }
18、#region
将Base64编码的文本转换成普通文本
将Base64编码的文本转换成普通文本
/// <summary> /// 将Base64编码的文本转换成普通文本 /// </summary> /// <param name="base64">Base64编码的文本</param> /// <returns></returns> public static string Base64StringToString(string base64) { if (base64 != "") { char[] charBuffer = base64.ToCharArray(); byte[] bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length); string returnstr = Encoding.Default.GetString(bytes); return returnstr; } else { return ""; } } #endregion #region 字符串转为base64字符串 public static string changebase64(string str) { if (str != "" && str != null) { byte[] b = Encoding.Default.GetBytes(str); string returnstr = Convert.ToBase64String(b); return returnstr; } else { return ""; } } #endregion
19、获取文件路径
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Contacts.plist" ofType:nil];
20、修改title的字体颜色
NSDictionary *dic = @{NSForegroundColorAttributeName : [UIColor whiteColor]}; self.navigationController.navigationBar.titleTextAttributes = dic;
21、添加头像的方法
//调用添加手势的方法
[self addTapGesture];
//给aImageView 视图添加轻拍手势
- (void)addTapGesture{ UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap : )]; [self.aview.aImageView addGestureRecognizer:tap]; [tap release]; }
//实现轻拍手势的方法
- (void)handleTap : (UITapGestureRecognizer *)tap{ //添加ActionSheet控件 提示选项框 UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从手机中选择", nil]; //在当前界面显示actionSheet对象 [actionSheet showInView:self.view]; [actionSheet release]; }
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{ switch (buttonIndex) { case 0: //拍照 NSLog(@"拍照"); [self pickerPictureFromCamera]; break; case 1: //从相册中读取照片 NSLog(@"从相册中读取照片"); [self pickerPictureFormPhotoAlbum]; break; default: break; } }
//拍照
- (void)pickerPictureFromCamera{ //判断前摄像头是否可以使用 BOOL isCameera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]; // UIImagePickerControllerCameraDeviceFront 前摄像头 // UIImagePickerControllerCameraDeviceRear //后摄像头 if (!isCameera) { NSLog(@"没有摄像头可以使用"); return; } //初始化图片选择控制器对象 UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init]; //设置图片选择器选取图片的样式 imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //设置取出来的图片是否允许编辑 imagePicker.allowsEditing = YES; //设置代理 imagePicker.delegate = self; //把手机相机推出来 [self presentViewController:imagePicker animated:YES completion:nil]; [imagePicker release]; }
//从相册中取出相片
- (void)pickerPictureFormPhotoAlbum{ UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init]; //设置图片格式 imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //设置允许编辑 imagePicker.allowsEditing = YES; //设置代理 imagePicker.delegate = self; [self presentViewController:imagePicker animated:YES completion:nil]; [imagePicker release]; }
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ //从字典中取出编辑的key值,对应的照片 self.aview.aImageView.image = [info objectForKey:UIImagePickerControllerEditedImage]; //自己推出来的自己收回去 [self dismissViewControllerAnimated:YES completion:nil]; }
================================================================================
22.NSUserDefaults适合存储轻量级的本地数据,比如要保存一个登陆界面的数据,用户名、密码之类的,个人觉得使用NSUserDefaults是首选。下次再登陆的时候就可以直接从NSUserDefaults里面读取上次登陆的信息咯。
因为如果使用自己建立的plist文件什么的,还得自己显示创建文件,读取文件,很麻烦,而是用NSUserDefaults则不用管这些东西,就像读字符串一样,直接读取就可以了。
NSUserDefaults支持的数据格式有:NSNumber(Integer、Float、Double),NSString,NSDate,NSArray,NSDictionary,BOOL类型
23.封装一个解析的方法:
//封装一个解析的方法
- (void)parserData : (NSData *)data{ //解析: NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; // NSLog(@"%@",dataDic); 验证! //取出results key值对应的数组 NSArray *array = dataDic[@"results"]; //遍历数组的字典,并使用给Business对象赋值 for (NSDictionary *dic in array) { //创建数据模型对象 Business *bus = [[Business alloc]init]; //使用kvc给bus赋值 [bus setValuesForKeysWithDictionary:dic]; //添加到存储所有商户信息的数组 [self.dataSource addObject:bus]; //释放 [bus release]; // NSLog(@"%@",self.dataSource); 验证! } //刷新ui界面 [self.tableView reloadData]; }
24、
'-[Person encodeWithCoder:]: unrecognized selector sent to instance 0x7fc831d9c880’
方法没实现
'-[Person encodeWithCoder:]: unrecognized selector sent to instance 0x7fc831d9c880’
方法没实现
25、计算字符串的大小:
+ (CGSize)getStringSize:(NSString *)text strMaxWidth:(CGFloat )width fontSize:(UIFont *)fontSize{ CGSize constraint = CGSizeMake(width, MAXFLOAT); NSDictionary *dict = [NSDictionary dictionaryWithObject:fontSize forKey: NSFontAttributeName]; CGSize size = CGSizeZero; if (isAboveIOS7) { size = [text boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dict context:nil].size; return size; } size = [text sizeWithFont:fontSize constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping]; return size; }
26、storyboard传值:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { //获取segue起始端的视图控制器对象 RootViewController *rootVC = [segue sourceViewController]; //通过segue完成跳转的时候会触发这个方法,在跳转之前触发,一般用来传值 //获取push过去后的视图控制器对象 DetailViewController *detailVC = [segue destinationViewController]; //把textField中的内容取出来赋值给下一个界面的属性 detailVC.string = rootVC.textField.text;// rootVC.textField.text 相当于 self.textField.text }
27.赋值方法中基本数据类型转字符串
self.ageLabel.text = [NSString stringWithFormat:@"%ld",person.age];
28.UIViewController中关于nib初始化的函数
- (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的事情。
guide 文档详细介绍了nib的装载过程,例如可以用loadNibNamed:owner方法,但是这个方法只是做了loadNib的事情。
29、解决webView的汉字显示问题
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://linode-back-cn.b0.upaiyun.com/articles/d34/372/db6edd24d68302930fbc5fd44c.html"]]]; [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自适应高度
UILabel *descLable=[[UILabel alloc] init]; [descLable setNumberOfLines:0]; descLable.lineBreakMode = UILineBreakModeCharacterWrap; descLable.text = _newsListModel.news_comtent; descLable.font = [UIFont systemFontOfSize:12]; UIFont *font = [UIFont fontWithName:@"Arial" size:12]; CGSize size = CGSizeMake(300, MAXFLOAT); CGSize labelsize = [_newsListModel.news_comtent sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeCharacterWrap]; [descLable setFrame:CGRectMake(10, 280,300, labelsize.height)]; [headView addSubview:descLable]; view.backgourd.color = [uicolor colorwithred green blue alpha:0.5]
————————————————————————————————————————————————————————————————————————
32、SDWebImage手动清除缓存的方法
1.找到SDImageCache类
2.添加如下方法:
[objc] view
plaincopy
plaincopy
- - (float)checkTmpSize
- {
- float totalSize = 0;
- NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:diskCachePath];
- for (NSString *fileName in fileEnumerator)
- {
- NSString *filePath = [diskCachePath stringByAppendingPathComponent:fileName];
- NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
- unsigned long long length = [attrs fileSize];
- totalSize += length / 1024.0 / 1024.0;
- }
- // NSLog(@"tmp size is %.2f",totalSize);
- return totalSize;
- }
新版的SDImageCache类,已增加此方法
[objc] view
plaincopy
plaincopy
- [[SDImageCache sharedImageCache] getSize];
3.在设置里这样使用
[objc] view
plaincopy
plaincopy
- #pragma 清理缓存图片
- - (void)clearTmpPics
- {
- [[SDImageCache sharedImageCache] clearDisk];
- // [[SDImageCache sharedImageCache] clearMemory];//可有可无
- DLog(@"clear disk");
- float tmpSize = [[SDImageCache sharedImageCache] checkTmpSize];
- NSString *clearCacheName = tmpSize >= 1 ? [NSString stringWithFormat:@"清理缓存(%.2fM)",tmpSize] : [NSString stringWithFormat:@"清理缓存(%.2fK)",tmpSize * 1024];
- [configDataArray replaceObjectAtIndex:2 withObject:clearCacheName];
- [configTableView reloadData];
- }
32、第三方MJ使用方法
1、只需修改环境中的footer和base -fobjc-arc
2、选中项目 - Project - Build Settings - ENABLE_STRICT_OBJC_MSGSEND 将其设置为 NO 即可
常用和易错的记录会持续更新..............敬请关注!