iOS开发中 常用枚举和常用的一些运算符(易错总结)
生活随笔
收集整理的這篇文章主要介紹了
iOS开发中 常用枚举和常用的一些运算符(易错总结)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1、色值的隨機(jī)值: #define kColorValue arc4random_uniform(256)/255.0
// arc4random_uniform(256)/255.0; 求出0.0~1.0之間的數(shù)字view.backgroundColor = [UIColor colorWithRed:kColorValue green: kColorValue blue: kColorValue alpha: 0.5];
2、定時(shí)器的使用: [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(fromOutToInside) userInfo:nil repeats:YES];
3、退回鍵盤(pán)觸發(fā)方法 - (BOOL)textFieldShouldReturn:(UITextField *)textField;{[textField resignFirstResponder];return YES; }
4、點(diǎn)擊空白回收鍵盤(pán) - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{for (int i = 0; i < 5; i ++ ) {[field resignFirstResponder]; }
5、UILabel切圓角,下面兩個(gè)同時(shí)才能顯示 ??? label.layer.cornerRadius = 10;//切圓角 ??? label.layer.masksToBounds = YES; 6、? UITextField文本框類型 (圓角) ??? textField.borderStyle = UITextBorderStyleRoundedRect; 7、定時(shí)器 [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(printHelloword) userInfo:nil repeats:YES];
8、UITextField 文本框的叉號(hào),X _field.clearButtonMode = UITextFieldViewModeAlways;
9、設(shè)置導(dǎo)航默認(rèn)標(biāo)題的顏色及字體大小 ? self.navigationController.navigationBar.titleTextAttributes = @{UITextAttributeTextColor: [UIColor whiteColor], UITextAttributeFont : [UIFont boldSystemFontOfSize:18]};
11、身份證號(hào)處理 - (NSString *)ittemDisposeIdcardNumber:(NSString *)idcardNumber {//星號(hào)字符串NSString *xinghaoStr = @"";//動(dòng)態(tài)計(jì)算星號(hào)的個(gè)數(shù)for (int i = 0; i < idcardNumber.length - 7; i++) {xinghaoStr = [xinghaoStr stringByAppendingString:@"*"];}//身份證號(hào)取前3后四中間以星號(hào)拼接idcardNumber = [NSString stringWithFormat:@"%@%@%@",[idcardNumber substringToIndex:3],xinghaoStr,[idcardNumber substringFromIndex:idcardNumber.length-4]];//返回處理好的身份證號(hào)return idcardNumber; }
---------------------------------------------------------------------------------------------------------- 12、//調(diào)整字間距 ? CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number;);[attributedString addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(0, [attributedString length])];//調(diào)整行間距[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [_messageLabel.text length])];_messageLabel.attributedText = attributedString;
---------------------------------------------------------------------- 13、ios8適配地圖授權(quán)問(wèn)題 iOS8修改了位置設(shè)置里的內(nèi)容,增加了一套狀態(tài)(使用中可用/通常可用),所以以前的CLLcationManage的注冊(cè)后,? Delegate接口不響應(yīng)了。? ? iOS8需要這么設(shè)置? 第一步? location = [[CLLocationManager alloc] init]; location.delegate= self; [locationrequestAlwaysAuthorization];
第二步? 在Plist中追加下面兩個(gè)字段 (必須有,最少一個(gè),內(nèi)容是系統(tǒng)ALert的文言,文言可為空)? 第三步? 有了新的Delegate方法。? - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { switch (status) { casekCLAuthorizationStatusNotDetermined: if ([location respondsToSelector:@selector(requestAlwaysAuthorization)]) { [locationrequestAlwaysAuthorization]; } break; default: break; } }
---------------------------------------------------------------------- 14、一段文字設(shè)置多種字體顏色 //設(shè)置不同字體顏色 -(void)fuwenbenLabel:(UILabel *)labell FontNumber:(id)font AndRange:(NSRange)range AndColor:(UIColor *)vaColor {NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:labell.text];//設(shè)置字號(hào)[str addAttribute:NSFontAttributeName value:font range:range];//設(shè)置文字顏色[str addAttribute:NSForegroundColorAttributeName value:vaColor range:range];labell.attributedText = str; }
---------------------------------------------------------------------- 15、由身份證號(hào)碼返回性別 -(NSString *)sexStrFromIdentityCard:(NSString *)numberStr{NSString *result = nil;BOOL isAllNumber = YES;if([numberStr length]<17)return result;//**截取第17為性別識(shí)別符NSString *fontNumer = [numberStr substringWithRange:NSMakeRange(16, 1)];//**檢測(cè)是否是數(shù)字;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開(kāi)發(fā)之獲取系統(tǒng)字體 + (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 {//判斷系統(tǒng)字體的size,返回使用的字體。UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]];return font; }
---------------------------------------------------------------------- 17、輸入字體,內(nèi)容。自動(dòng)算范圍 內(nèi)容:字符串,輸入字體大小,和需要多寬 CGSize size1 = [內(nèi)容 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編碼的文本轉(zhuǎn)換成普通文本 /// <summary>/// 將Base64編碼的文本轉(zhuǎn)換成普通文本/// </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 字符串轉(zhuǎn)為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、添加頭像的方法 //調(diào)用添加手勢(shì)的方法 [self addTapGesture];
//給aImageView 視圖添加輕拍手勢(shì)
- (void)addTapGesture{UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap : )];[self.aview.aImageView addGestureRecognizer:tap];[tap release];}
//實(shí)現(xiàn)輕拍手勢(shì)的方法
- (void)handleTap : (UITapGestureRecognizer *)tap{ //添加ActionSheet控件 提示選項(xiàng)框UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"從手機(jī)中選擇", nil];//在當(dāng)前界面顯示actionSheet對(duì)象[actionSheet showInView:self.view];[actionSheet release]; }
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{switch (buttonIndex) {case 0://拍照NSLog(@"拍照");[self pickerPictureFromCamera];break;case 1://從相冊(cè)中讀取照片NSLog(@"從相冊(cè)中讀取照片");[self pickerPictureFormPhotoAlbum];break;default:break;}}
//拍照
- (void)pickerPictureFromCamera{//判斷前攝像頭是否可以使用 BOOL isCameera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]; // UIImagePickerControllerCameraDeviceFront 前攝像頭 // UIImagePickerControllerCameraDeviceRear //后攝像頭if (!isCameera) {NSLog(@"沒(méi)有攝像頭可以使用");return;}//初始化圖片選擇控制器對(duì)象UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];//設(shè)置圖片選擇器選取圖片的樣式imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//設(shè)置取出來(lái)的圖片是否允許編輯imagePicker.allowsEditing = YES;//設(shè)置代理imagePicker.delegate = self;//把手機(jī)相機(jī)推出來(lái)[self presentViewController:imagePicker animated:YES completion:nil];[imagePicker release];}
//從相冊(cè)中取出相片
- (void)pickerPictureFormPhotoAlbum{UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];//設(shè)置圖片格式imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//設(shè)置允許編輯imagePicker.allowsEditing = YES;//設(shè)置代理imagePicker.delegate = self;[self presentViewController:imagePicker animated:YES completion:nil];[imagePicker release];}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{//從字典中取出編輯的key值,對(duì)應(yīng)的照片self.aview.aImageView.image = [info objectForKey:UIImagePickerControllerEditedImage];//自己推出來(lái)的自己收回去[self dismissViewControllerAnimated:YES completion:nil]; }
================================================================================ 22.NSUserDefaults適合存儲(chǔ)輕量級(jí)的本地?cái)?shù)據(jù),比如要保存一個(gè)登陸界面的數(shù)據(jù),用戶名、密碼之類的,個(gè)人覺(jué)得使用NSUserDefaults是首選。下次再登陸的時(shí)候就可以直接從NSUserDefaults里面讀取上次登陸的信息咯。
因?yàn)槿绻褂米约航⒌膒list文件什么的,還得自己顯示創(chuàng)建文件,讀取文件,很麻煩,而是用NSUserDefaults則不用管這些東西,就像讀字符串一樣,直接讀取就可以了。
NSUserDefaults支持的數(shù)據(jù)格式有:NSNumber(Integer、Float、Double),NSString,NSDate,NSArray,NSDictionary,BOOL類型 23.封裝一個(gè)解析的方法: //封裝一個(gè)解析的方法 - (void)parserData : (NSData *)data{//解析:NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];// NSLog(@"%@",dataDic); 驗(yàn)證!//取出results key值對(duì)應(yīng)的數(shù)組NSArray *array = dataDic[@"results"];//遍歷數(shù)組的字典,并使用給Business對(duì)象賦值for (NSDictionary *dic in array) {//創(chuàng)建數(shù)據(jù)模型對(duì)象Business *bus = [[Business alloc]init];//使用kvc給bus賦值[bus setValuesForKeysWithDictionary:dic];//添加到存儲(chǔ)所有商戶信息的數(shù)組[self.dataSource addObject:bus];//釋放[bus release];// NSLog(@"%@",self.dataSource); 驗(yàn)證! }//刷新ui界面[self.tableView reloadData]; }
24、 '-[Person encodeWithCoder:]: unrecognized selector sent to instance 0x7fc831d9c880’? ?方法沒(méi)實(shí)現(xiàn) 25、計(jì)算字符串的大小: + (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:constraintoptions:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeadingattributes:dictcontext:nil].size;return size;}size = [text sizeWithFont:fontSizeconstrainedToSize:constraintlineBreakMode:NSLineBreakByWordWrapping];return size; }
26、storyboard傳值: - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {//獲取segue起始端的視圖控制器對(duì)象RootViewController *rootVC = [segue sourceViewController];//通過(guò)segue完成跳轉(zhuǎn)的時(shí)候會(huì)觸發(fā)這個(gè)方法,在跳轉(zhuǎn)之前觸發(fā),一般用來(lái)傳值//獲取push過(guò)去后的視圖控制器對(duì)象DetailViewController *detailVC = [segue destinationViewController];//把textField中的內(nèi)容取出來(lái)賦值給下一個(gè)界面的屬性detailVC.string = rootVC.textField.text;// rootVC.textField.text 相當(dāng)于 self.textField.text }
27.賦值方法中基本數(shù)據(jù)類型轉(zhuǎn)字符串 ? self.ageLabel.text = [NSString stringWithFormat:@"%ld",person.age];
28.UIViewController中關(guān)于nib初始化的函數(shù)
29、解決webView的漢字顯示問(wèn)題 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?登陸注銷功能的實(shí)現(xiàn)
1、在appDelegate中加入一個(gè)navigation用來(lái)控制所有的頁(yè)面跳轉(zhuǎn) 2、將login頁(yè)面作為navigation的root view 3、在appDelegate中判斷程序是否是第一次登陸,如果是直接進(jìn)入login頁(yè)面,如果不是則跳過(guò)login頁(yè)面,push下一個(gè)頁(yè)面(程序主頁(yè)面,且采用的是tab+nav的結(jié)構(gòu)) 4、程序主頁(yè)面中對(duì)應(yīng)的每個(gè)tab頁(yè)面都是一個(gè)nav的結(jié)構(gòu) 5、當(dāng)點(diǎn)擊注銷按鈕時(shí),利用appDelegate中的導(dǎo)航將主頁(yè)面pop出來(lái),此時(shí)程序便又重新回到了login頁(yè)面。
31.Label自適應(yīng)高度
———————————————————————————————————————————————————————————————————————— 32、SDWebImage手動(dòng)清除緩存的方法
1.找到SDImageCache類
-?(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?sharedImageCache]?getSize];?? 3.在設(shè)置里這樣使用
[objc]?view plaincopy #pragma?清理緩存圖片?? ?? -?(void)clearTmpPics?? {?? ????[[SDImageCache?sharedImageCache]?clearDisk];?? ?? //????[[SDImageCache?sharedImageCache]?clearMemory];//可有可無(wú)?? ?? ????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、只需修改環(huán)境中的footer和base ? -fobjc-arc
2、選中項(xiàng)目?-?Project?-?Build?Settings?-?ENABLE_STRICT_OBJC_MSGSEND? 將其設(shè)置為?NO?即可
常用和易錯(cuò)的記錄會(huì)持續(xù)更新..............敬請(qǐng)關(guān)注!
2、定時(shí)器的使用: [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(fromOutToInside) userInfo:nil repeats:YES];
3、退回鍵盤(pán)觸發(fā)方法 - (BOOL)textFieldShouldReturn:(UITextField *)textField;{[textField resignFirstResponder];return YES; }
4、點(diǎn)擊空白回收鍵盤(pán) - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{for (int i = 0; i < 5; i ++ ) {[field resignFirstResponder]; }
5、UILabel切圓角,下面兩個(gè)同時(shí)才能顯示 ??? label.layer.cornerRadius = 10;//切圓角 ??? label.layer.masksToBounds = YES; 6、? UITextField文本框類型 (圓角) ??? textField.borderStyle = UITextBorderStyleRoundedRect; 7、定時(shí)器 [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(printHelloword) userInfo:nil repeats:YES];
8、UITextField 文本框的叉號(hào),X _field.clearButtonMode = UITextFieldViewModeAlways;
9、設(shè)置導(dǎo)航默認(rèn)標(biāo)題的顏色及字體大小 ? self.navigationController.navigationBar.titleTextAttributes = @{UITextAttributeTextColor: [UIColor whiteColor], UITextAttributeFont : [UIFont boldSystemFontOfSize:18]};
11、身份證號(hào)處理 - (NSString *)ittemDisposeIdcardNumber:(NSString *)idcardNumber {//星號(hào)字符串NSString *xinghaoStr = @"";//動(dòng)態(tài)計(jì)算星號(hào)的個(gè)數(shù)for (int i = 0; i < idcardNumber.length - 7; i++) {xinghaoStr = [xinghaoStr stringByAppendingString:@"*"];}//身份證號(hào)取前3后四中間以星號(hào)拼接idcardNumber = [NSString stringWithFormat:@"%@%@%@",[idcardNumber substringToIndex:3],xinghaoStr,[idcardNumber substringFromIndex:idcardNumber.length-4]];//返回處理好的身份證號(hào)return idcardNumber; }
---------------------------------------------------------------------------------------------------------- 12、//調(diào)整字間距 ? CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number;);[attributedString addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(0, [attributedString length])];//調(diào)整行間距[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [_messageLabel.text length])];_messageLabel.attributedText = attributedString;
---------------------------------------------------------------------- 13、ios8適配地圖授權(quán)問(wèn)題 iOS8修改了位置設(shè)置里的內(nèi)容,增加了一套狀態(tài)(使用中可用/通常可用),所以以前的CLLcationManage的注冊(cè)后,? Delegate接口不響應(yīng)了。? ? iOS8需要這么設(shè)置? 第一步? location = [[CLLocationManager alloc] init]; location.delegate= self; [locationrequestAlwaysAuthorization];
第二步? 在Plist中追加下面兩個(gè)字段 (必須有,最少一個(gè),內(nèi)容是系統(tǒng)ALert的文言,文言可為空)? 第三步? 有了新的Delegate方法。? - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { switch (status) { casekCLAuthorizationStatusNotDetermined: if ([location respondsToSelector:@selector(requestAlwaysAuthorization)]) { [locationrequestAlwaysAuthorization]; } break; default: break; } }
---------------------------------------------------------------------- 14、一段文字設(shè)置多種字體顏色 //設(shè)置不同字體顏色 -(void)fuwenbenLabel:(UILabel *)labell FontNumber:(id)font AndRange:(NSRange)range AndColor:(UIColor *)vaColor {NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:labell.text];//設(shè)置字號(hào)[str addAttribute:NSFontAttributeName value:font range:range];//設(shè)置文字顏色[str addAttribute:NSForegroundColorAttributeName value:vaColor range:range];labell.attributedText = str; }
---------------------------------------------------------------------- 15、由身份證號(hào)碼返回性別 -(NSString *)sexStrFromIdentityCard:(NSString *)numberStr{NSString *result = nil;BOOL isAllNumber = YES;if([numberStr length]<17)return result;//**截取第17為性別識(shí)別符NSString *fontNumer = [numberStr substringWithRange:NSMakeRange(16, 1)];//**檢測(cè)是否是數(shù)字;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開(kāi)發(fā)之獲取系統(tǒng)字體 + (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 {//判斷系統(tǒng)字體的size,返回使用的字體。UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]];return font; }
---------------------------------------------------------------------- 17、輸入字體,內(nèi)容。自動(dòng)算范圍 內(nèi)容:字符串,輸入字體大小,和需要多寬 CGSize size1 = [內(nèi)容 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編碼的文本轉(zhuǎn)換成普通文本 /// <summary>/// 將Base64編碼的文本轉(zhuǎn)換成普通文本/// </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 字符串轉(zhuǎn)為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、添加頭像的方法 //調(diào)用添加手勢(shì)的方法 [self addTapGesture];
//給aImageView 視圖添加輕拍手勢(shì)
- (void)addTapGesture{UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap : )];[self.aview.aImageView addGestureRecognizer:tap];[tap release];}
//實(shí)現(xiàn)輕拍手勢(shì)的方法
- (void)handleTap : (UITapGestureRecognizer *)tap{ //添加ActionSheet控件 提示選項(xiàng)框UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"從手機(jī)中選擇", nil];//在當(dāng)前界面顯示actionSheet對(duì)象[actionSheet showInView:self.view];[actionSheet release]; }
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{switch (buttonIndex) {case 0://拍照NSLog(@"拍照");[self pickerPictureFromCamera];break;case 1://從相冊(cè)中讀取照片NSLog(@"從相冊(cè)中讀取照片");[self pickerPictureFormPhotoAlbum];break;default:break;}}
//拍照
- (void)pickerPictureFromCamera{//判斷前攝像頭是否可以使用 BOOL isCameera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]; // UIImagePickerControllerCameraDeviceFront 前攝像頭 // UIImagePickerControllerCameraDeviceRear //后攝像頭if (!isCameera) {NSLog(@"沒(méi)有攝像頭可以使用");return;}//初始化圖片選擇控制器對(duì)象UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];//設(shè)置圖片選擇器選取圖片的樣式imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//設(shè)置取出來(lái)的圖片是否允許編輯imagePicker.allowsEditing = YES;//設(shè)置代理imagePicker.delegate = self;//把手機(jī)相機(jī)推出來(lái)[self presentViewController:imagePicker animated:YES completion:nil];[imagePicker release];}
//從相冊(cè)中取出相片
- (void)pickerPictureFormPhotoAlbum{UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];//設(shè)置圖片格式imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//設(shè)置允許編輯imagePicker.allowsEditing = YES;//設(shè)置代理imagePicker.delegate = self;[self presentViewController:imagePicker animated:YES completion:nil];[imagePicker release];}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{//從字典中取出編輯的key值,對(duì)應(yīng)的照片self.aview.aImageView.image = [info objectForKey:UIImagePickerControllerEditedImage];//自己推出來(lái)的自己收回去[self dismissViewControllerAnimated:YES completion:nil]; }
================================================================================ 22.NSUserDefaults適合存儲(chǔ)輕量級(jí)的本地?cái)?shù)據(jù),比如要保存一個(gè)登陸界面的數(shù)據(jù),用戶名、密碼之類的,個(gè)人覺(jué)得使用NSUserDefaults是首選。下次再登陸的時(shí)候就可以直接從NSUserDefaults里面讀取上次登陸的信息咯。
因?yàn)槿绻褂米约航⒌膒list文件什么的,還得自己顯示創(chuàng)建文件,讀取文件,很麻煩,而是用NSUserDefaults則不用管這些東西,就像讀字符串一樣,直接讀取就可以了。
NSUserDefaults支持的數(shù)據(jù)格式有:NSNumber(Integer、Float、Double),NSString,NSDate,NSArray,NSDictionary,BOOL類型 23.封裝一個(gè)解析的方法: //封裝一個(gè)解析的方法 - (void)parserData : (NSData *)data{//解析:NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];// NSLog(@"%@",dataDic); 驗(yàn)證!//取出results key值對(duì)應(yīng)的數(shù)組NSArray *array = dataDic[@"results"];//遍歷數(shù)組的字典,并使用給Business對(duì)象賦值for (NSDictionary *dic in array) {//創(chuàng)建數(shù)據(jù)模型對(duì)象Business *bus = [[Business alloc]init];//使用kvc給bus賦值[bus setValuesForKeysWithDictionary:dic];//添加到存儲(chǔ)所有商戶信息的數(shù)組[self.dataSource addObject:bus];//釋放[bus release];// NSLog(@"%@",self.dataSource); 驗(yàn)證! }//刷新ui界面[self.tableView reloadData]; }
24、 '-[Person encodeWithCoder:]: unrecognized selector sent to instance 0x7fc831d9c880’? ?方法沒(méi)實(shí)現(xiàn) 25、計(jì)算字符串的大小: + (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:constraintoptions:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeadingattributes:dictcontext:nil].size;return size;}size = [text sizeWithFont:fontSizeconstrainedToSize:constraintlineBreakMode:NSLineBreakByWordWrapping];return size; }
26、storyboard傳值: - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {//獲取segue起始端的視圖控制器對(duì)象RootViewController *rootVC = [segue sourceViewController];//通過(guò)segue完成跳轉(zhuǎn)的時(shí)候會(huì)觸發(fā)這個(gè)方法,在跳轉(zhuǎn)之前觸發(fā),一般用來(lái)傳值//獲取push過(guò)去后的視圖控制器對(duì)象DetailViewController *detailVC = [segue destinationViewController];//把textField中的內(nèi)容取出來(lái)賦值給下一個(gè)界面的屬性detailVC.string = rootVC.textField.text;// rootVC.textField.text 相當(dāng)于 self.textField.text }
27.賦值方法中基本數(shù)據(jù)類型轉(zhuǎn)字符串 ? self.ageLabel.text = [NSString stringWithFormat:@"%ld",person.age];
28.UIViewController中關(guān)于nib初始化的函數(shù)
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil; 從這個(gè)函數(shù)的說(shuō)明我們可以知道,如果你subclass一個(gè)UIViewController,不管有沒(méi)有使用NIB, [super?initWithNibName:bundle]這個(gè)方法必須被調(diào)用, 這個(gè)方法會(huì)在如下兩種情況下被調(diào)用:
- 顯示調(diào)用, 指定一個(gè)nib名稱,系統(tǒng)會(huì)去找指定的nib
- 在父類的Init方法中被調(diào)用,如果這種情況,兩個(gè)參數(shù)都會(huì)是nil,系統(tǒng)會(huì)去找和你自定以的UIViewController相同名字的nib
NSBundle Nib裝載方法
Resource programming guide?文檔詳細(xì)介紹了nib的裝載過(guò)程,例如可以用loadNibNamed:owner方法,但是這個(gè)方法只是做了loadNib的事情。29、解決webView的漢字顯示問(wèn)題 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?登陸注銷功能的實(shí)現(xiàn)
1、在appDelegate中加入一個(gè)navigation用來(lái)控制所有的頁(yè)面跳轉(zhuǎn) 2、將login頁(yè)面作為navigation的root view 3、在appDelegate中判斷程序是否是第一次登陸,如果是直接進(jìn)入login頁(yè)面,如果不是則跳過(guò)login頁(yè)面,push下一個(gè)頁(yè)面(程序主頁(yè)面,且采用的是tab+nav的結(jié)構(gòu)) 4、程序主頁(yè)面中對(duì)應(yīng)的每個(gè)tab頁(yè)面都是一個(gè)nav的結(jié)構(gòu) 5、當(dāng)點(diǎn)擊注銷按鈕時(shí),利用appDelegate中的導(dǎo)航將主頁(yè)面pop出來(lái),此時(shí)程序便又重新回到了login頁(yè)面。
31.Label自適應(yīng)高度
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手動(dòng)清除緩存的方法
1.找到SDImageCache類
2.添加如下方法:
[objc]?view plaincopy新版的SDImageCache類,已增加此方法
[objc]?view plaincopy[objc]?view plaincopy
32、第三方MJ使用方法 1、只需修改環(huán)境中的footer和base ? -fobjc-arc
2、選中項(xiàng)目?-?Project?-?Build?Settings?-?ENABLE_STRICT_OBJC_MSGSEND? 將其設(shè)置為?NO?即可
常用和易錯(cuò)的記錄會(huì)持續(xù)更新..............敬請(qǐng)關(guān)注!
總結(jié)
以上是生活随笔為你收集整理的iOS开发中 常用枚举和常用的一些运算符(易错总结)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: WAP端 touch事件触发顺序记录
- 下一篇: Spring+Quartz(一)