一、調用代碼使APP進入后臺,達到點擊Home鍵的效果。(私有API)
[[UIapplication sharedApplication] performSelector:@selector(suspend)];suspend的英文意思有:暫停; 懸; 掛; 延緩;
二、帶有中文的URL處理。
大概舉個例子,類似下面的URL,里面直接含有中文,可能導致播放不了,那么我們要處理一個這個URL,因為他太操蛋了,居然用中文。
http://static.tripbe.com/videofiles/視頻/我的自拍視頻.mp4NSString *path = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)model.mp4_url, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));三、獲取UIWebView的高度 個人最常用的獲取方法,感覺這個比較靠譜
- (void)webViewDidFinishLoad:(UIWebView *)webView { CGFloat height = [[webView stringByEvaluatingjavaScriptFromString:@"document.body.offsetHeight"] floatValue]; CGRect frame = webView.frame; webView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height); } 四、給UIView設置圖片(UILabel一樣適用)
第一種方法: 利用的UIView的設置背景顏色方法,用圖片做圖案顏色,然后傳給背景顏色。
UIColor *bgColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"bgImg.png"]; UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,480)];[myView setBackGroundColor:bgColor];第二種方法:
UIImage *image = [UIImage imageNamed:@"yourPicName@2x.png"];yourView.layer.contents = (__bridge id)image.CGImage;//設置顯示的圖片范圍yourView.layer.contentsCenter = CGRectMake(0.25,0.25,0.5,0.5);//四個值在0-1之間,對應的為x,y,width,height。五、去掉UITableView多余的分割線
yourTableView.tableFooterView = [UIView new];六、調整cell分割線的位置,兩個方法一起用,暴力解決,防脫發
-(void)viewDidLayoutSubviews { if ([self.mytableview respondsToSelector:@selector(setSeparatorInset:)]) { [self.mytableview setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)]; } if ([self.mytableview respondsToSelector:@selector(setLayoutMargins:)]) { [self.mytableview setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)]; }}#PRagma mark - cell分割線- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{ if ([cell respondsToSelector:@selector(setSeparatorInset:)]){ [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)]; } if ([cell respondsToSelector:@selector(setLayoutMargins:)]) { [cell setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)]; }}七、UILabel和UIImageView的交互userInteractionEabled默認為NO。那么如果你把這兩個類做為父試圖的話,里面的所有東東都不可以點擊哦。曾經有一個人,讓我幫忙調試bug,他調試很久沒搞定,就是把WMPlayer對象(播放器對象)放到一個UIImageView上面。這樣imageView addSubView:wmPlayer 后,播放器的任何東東都不能點擊了。userInteractionEabled設置為YES即可。
八、UISearchController和UISearchBar的Cancle按鈕改title問題,簡單粗暴
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{ searchController.searchBar.showsCancelButton = YES; UIButton *canceLBtn = [searchController.searchBar valueForKey:@"cancelButton"]; [canceLBtn setTitle:@"取消" forState:UIControlStateNormal]; [canceLBtn setTitleColor:[UIColor colorWithRed:14.0/255.0 green:180.0/255.0 blue:0.0/255.0 alpha:1.00] forState:UIControlStateNormal]; searchBar.showsCancelButton = YES; return YES;}九、UITableView收起鍵盤何必這么麻煩 一個屬性搞定,效果好(UIScrollView同樣可以使用) 以前是不是覺得[self.view endEditing:YES];很屌,這個下面的更屌。 yourTableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
另外一個枚舉為UIScrollViewKeyboardDismissModeInteractive,表示在鍵盤內部滑動,鍵盤逐漸下去。
十、NSTimer 1、NSTimer計算的時間并不精確 2、NSTimer需要添加到runLoop運行才會執行,但是這個runLoop的線程必須是已經開啟。 3、NSTimer會對它的tagert進行retain,我們必須對其重復性的使用intvailte停止。target如果是self(指UIViewController),那么VC的retainCount+1,如果你不釋放NSTimer,那么你的VC就不會dealloc了,內存泄漏了。
十一、UIViewController沒用大小(frame) 經常有人在群里問:怎么改變VC的大小??? 瞬間無語。(只有UIView才能設置大小,VC是控制器啊,哥?。?/p>
十二、用十六進制獲取UIColor(類方法或者Category都可以,這里我用工具類方法)
+ (UIColor *)colorWithHexString:(NSString *)color{ NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString]; // String should be 6 or 8 characters if ([cString length] < 6) { return [UIColor clearColor]; } // strip 0X if it appears if ([cString hasprefix:@"0X"]) cString = [cString substringFromIndex:2]; if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1]; if ([cString length] != 6) return [UIColor clearColor]; // Separate into r, g, b substrings NSRange range; range.location = 0; range.length = 2; //r NSString *rString = [cString substringWithRange:range]; //g range.location = 2; NSString *gString = [cString substringWithRange:range]; //b range.location = 4; NSString *bString = [cString substringWithRange:range]; // Scan values unsigned int r, g, b; [[NSScanner scannerWithString:rString] scanHexInt:&r]; [[NSScanner scannerWithString:gString] scanHexInt:&g]; [[NSScanner scannerWithString:bString] scanHexInt:&b]; return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];}十三、獲取今天是星期幾
+ (NSString *) getweekDayStringWithDate:(NSDate *) date{ NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; // 指定日歷的算法 NSDateComponents *comps = [calendar components:NSWeekdayCalendarUnit fromDate:date]; // 1 是周日,2是周一 3.以此類推 NSNumber * weekNumber = @([comps weekday]); NSInteger weekInt = [weekNumber integerValue]; NSString *weekDayString = @"(周一)"; switch (weekInt) { case 1: { weekDayString = @"(周日)"; } break; case 2: { weekDayString = @"(周一)"; } break; case 3: { weekDayString = @"(周二)"; } break; case 4: { weekDayString = @"(周三)"; } break; case 5: { weekDayString = @"(周四)"; } break; case 6: { weekDayString = @"(周五)"; } break; case 7: { weekDayString = @"(周六)"; } break; default: break; } return weekDayString;}十四、UIView的部分圓角問題
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(120, 10, 80, 80)];view2.backgroundColor = [UIColor redColor];[self.view addSubview:view2];UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view2.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];maskLayer.frame = view2.bounds;maskLayer.path = maskPath.CGPath;view2.layer.mask = maskLayer;//其中,byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight//指定了需要成為圓角的角。該參數是UIRectCorner類型的,可選的值有:* UIRectCornerTopLeft* UIRectCornerTopRight* UIRectCornerBottomLeft* UIRectCornerBottomRight* UIRectCornerAllCorners從名字很容易看出來代表的意思,使用“|”來組合就好了。
十五、設置滑動的時候隱藏navigationBar
navigationController.hidesBarsOnSwipe = Yes;十六、iOS畫虛線 記得先 QuartzCore框架的導入
#import <QuartzCore/QuartzCore.h>CGContextRef context =UIGraphicsGetCurrentContext(); CGContextBeginPath(context); CGContextSetLineWidth(context, 2.0); CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor); CGFloat lengths[] = {10,10}; CGContextSetLineDash(context, 0, lengths,2); CGContextMoveToPoint(context, 10.0, 20.0); CGContextAddLineToPoint(context, 310.0,20.0); CGContextStrokePath(context); CGContextClosePath(context); 十七、自動布局中多行UILabel,需要設置其preferredMaxLayoutWidth屬性才能正常顯示多行內容。另外如果出現顯示不全文本,可以在計算的結果基礎上+0.5。
CGFloat h = [model.message boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - kGAP-kAvatar_Size - 2*kGAP, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.height+0.5;十八、 禁止程序運行時自動鎖屏 [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
十九、KVC相關,支持操作符 KVC同時還提供了很復雜的函數,主要有下面這些 ①簡單集合運算符 簡單集合運算符共有@avg, @count , @max , @min ,@sum5種,都表示啥不用我說了吧, 目前還不支持自定義。
@interface Book : NSObject@property (nonatomic,copy) NSString* name;@property (nonatomic,assign) CGFloat price;@end@implementation Book@endBook *book1 = [Book new];book1.name = @"The Great Gastby";book1.price = 22;Book *book2 = [Book new];book2.name = @"Time History";book2.price = 12;Book *book3 = [Book new];book3.name = @"Wrong Hole";book3.price = 111;Book *book4 = [Book new];book4.name = @"Wrong Hole";book4.price = 111;NSArray* arrBooks = @[book1,book2,book3,book4];NSNumber* sum = [arrBooks valueForKeyPath:@"@sum.price"];NSLog(@"sum:%f",sum.floatValue);NSNumber* avg = [arrBooks valueForKeyPath:@"@avg.price"];NSLog(@"avg:%f",avg.floatValue);NSNumber* count = [arrBooks valueForKeyPath:@"@count"];NSLog(@"count:%f",count.floatValue);NSNumber* min = [arrBooks valueForKeyPath:@"@min.price"];NSLog(@"min:%f",min.floatValue);NSNumber* max = [arrBooks valueForKeyPath:@"@max.price"];NSLog(@"max:%f",max.floatValue);打印結果2016-04-20 16:45:54.696 KVCDemo[1484:127089] sum:256.0000002016-04-20 16:45:54.697 KVCDemo[1484:127089] avg:64.0000002016-04-20 16:45:54.697 KVCDemo[1484:127089] count:4.0000002016-04-20 16:45:54.697 KVCDemo[1484:127089] min:12.000000NSArray 快速求總和 最大值 最小值 和 平均值
NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];NSLog(@"%f/n%f/n%f/n%f",sum,avg,max,min);二十、使用MBProgressHud時,盡量不要加到UIWindow上,加self.view上即可。如果加UIWindow上在iPad上,旋轉屏幕的時候MBProgressHud不會旋轉。之前有人遇到這個bug,我讓他改放到self.view上即可解決此bug。
二十一、強制讓App直接退出(非閃退,非崩潰)
- (void)exitApplication { AppDelegate *app = [UIApplication sharedApplication].delegate; UIWindow *window = app.window; [UIView animateWithDuration:1.0f animations:^{ window.alpha = 0; } completion:^(BOOL finished) { exit(0); }]; }二十二、Label行間距
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.contentLabel.text]; NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; [paragraphStyle setLineSpacing:3]; //調整行間距 [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.contentLabel.text length])]; self.contentLabel.attributedText = attributedString;二十三、CocoaPods pod install/pod update更新慢的問題 pod install –verbose –no-repo-update pod update –verbose –no-repo-update 如果不加后面的參數,默認會升級CocoaPods的spec倉庫,加一個參數可以省略這一步,然后速度就會提升不少。
二十四、MRC和ARC混編設置方式 在XCode中targets的build phases選項下Compile Sources下選擇 不需要arc編譯的文件 雙擊輸入 -fno-objc-arc 即可 MRC工程中也可以使用ARC的類,方法如下: 在XCode中targets的build phases選項下Compile Sources下選擇要使用arc編譯的文件 雙擊輸入 -fobjc-arc 即可
二十五、把tableview里cell的小對勾的顏色改成別的顏色 _yourTableView.tintColor = [UIColor redColor];
二十六、解決同時按兩個按鈕進兩個view的問題 [button setExclusiveTouch:YES];
二十七、修改textFieldplaceholder字體顏色和大小
textField.placeholder = @"請輸入用戶名"; [textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"]; [textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];二十八、禁止textField和textView的復制粘貼菜單
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{ if ([UIMenuController sharedMenuController]) { [UIMenuController sharedMenuController].menuVisible = NO; } return NO;}二十九:如何進入我的軟件在app store 的頁面 先用iTunes Link Maker找到軟件在訪問地址,格式為itms-apps://ax.itunes.apple.com/…,然后
#define ITUNESLINK @"itms-apps://ax.itunes.apple.com/..."NSURL *url = [NSURL URLWithString:ITUNESLINK];if([[UIApplication sharedApplication] canOpenURL:url]){ [[UIApplication sharedApplication] openURL:url];}如果把上述地址中itms-apps改為http就可以在瀏覽器中打開了??梢园堰@個地址放在自己的網站里,鏈接到app store。 iTunes Link Maker地址:http://itunes.apple.com/linkmaker
三十、二級三級頁面隱藏系統tabbar 1、單個處理
YourViewController *yourVC = [YourViewController new];yourVC.hidesBottomBarWhenPushed = YES;[self.navigationController pushViewController:yourVC animated:YES];2.統一在基類里面處理 新建一個類BaseNavigationController繼承UINavigationController,然后重寫 -(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated這個方法。所有的push事件都走此方法。
@interface BaseNavigationController : UINavigationController@end -(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{ [super pushViewController:viewController animated:animated]; if (self.viewControllers.count>1) { viewController.hidesBottomBarWhenPushed = YES; } }三十一、取消系統的返回手勢
self.navigationController.interactivePopGestureRecognizer.enabled = NO;三十二、修改UIWebView中字體的大小,顏色
1、UIWebView設置字體大小,顏色,字體: UIWebView無法通過自身的屬性設置字體的一些屬性,只能通過html代碼進行設置 在webView加載完畢后,在
- (void)webViewDidFinishLoad:(UIWebView *)webView方法中加入js代碼 NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '60%'"; [_webView stringByEvaluatingJavascriptFromString:str]; 或者加入以下代碼
NSString *jsString = [[NSString alloc] initWithFormat:@"document.body.style.fontSize=%f;document.body.style.color=%@",fontSize,fontColor]; [webView stringByEvaluatingJavaScriptFromString:jsString]; 三十三、NSString處理技巧 使用場景舉例:可以用在處理用戶用戶輸入在UITextField的文本
//待處理的字符串NSString *string = @" A B CD EFG/n MN/n";//字符串替換,處理后的string1 = @"ABCDEF/nMN/n";NSString *string1 = [string stringByReplacingOccurrencesOfString:@" " withString:@""];//去除兩端空格(注意是兩端),處理后的string2 = @"A B CD EFG/n MN/n";NSString *string2 = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];//去除兩端回車(注意是兩端),處理后的string3 = @" A B CD EFG/n MN";NSString *string3 = [string stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];//去除兩端空格和回車(注意是兩端),處理后的string4 = @"A B CD EFG/n MN";NSString *string4 = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];三十四、主線程操作UI(對UI進行更新只能在主線程進行) 解釋:所謂的在主線程更新UI、操作UI,大致的意思就是設置UILabel的text或者設置tabbar的badgeValue,設置UIImageView的image等等。
回到主線程方式1:
[self performSelectorOnMainThread:@selector(updateImage:) withObject:data waitUntilDone:YES];performSelectorOnMainThread方法是NSObject的分類方法,每個NSObject對象都有此方法, 它調用的selector方法是當前調用控件的方法,例如使用UIImageView調用的時候selector就是UIImageView的方法 Object:代表調用方法的參數,不過只能傳遞一個參數(如果有多個參數請使用對象進行封裝) waitUntilDone:是否線程任務完成執行
回到主線程方式2:
dispatch_async(dispatch_get_main_queue(), ^{ //更新UI的代碼 });這個不多解釋,GCD的方法,注意不要在主線程掉用。
三十五、判斷模擬器
if (TARGET_IPHONE_SIMULATOR) { NSLog(@"是模擬器"); }else{ NSLog(@"不是模擬器"); }三十六、真機測試報 TCWeiboSDK 93 duplicate symbols for architecture armv7
這是因為在項目中引用的兩個相同的類庫引起了,在我的項目中是因為引入的兩個不同指令集引起的;
三十七、AFnetWorking報”Request failed: unacceptable content-type: text/html”錯誤
AFURLResponseSerialization.m文件設置
self.acceptableContentTypes = [NSSetsetWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];加上@”text/html”,部分,其實就是添加一種服務器返回的數據格式。
三十八、隱藏navigation跳轉后的返回按鈕
//隱藏頭部左邊的返回self.navigationItem.hidesBackButton=YES;三十九、兩種方法刪除NSUserDefaults所有記錄
//方法一NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];//方法二- (void)resetDefaults { NSUserDefaults * defs = [NSUserDefaults standardUserDefaults]; NSDictionary * dict = [defs dictionaryRepresentation]; for (id key in dict) { [defs removeObjectForKey:key]; } [defs synchronize];}四十、UITableView設置Section間距 在使用UITableViewStyleGrouped類型的UITableView的時候,經常很奇怪的出現多余的section間距,那可能是因為你只設置了footer或者header的間距中的其中一個,那么另一個默認為20個高度,只需要設置返回0.001的CGFlot的浮點數就可以解決這個多余的間距。
//Header底部間距- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 40;//section頭部高度 } //footer底部間距 - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section { return 0.001; } 四十一、NSLog 輸出格式集合
? %@ 對象? %d, %i 整數? %u 無符整形? %f 浮點/雙字? %x, %X 二進制整數? %o 八進制整數? %zu size_t? %p 指針? %e 浮點/雙字 (科學計算)? %g 浮點/雙字? %s C 字符串? %.*s Pascal字符串? %c 字符? %C unichar? %lld 64位長整數(long long)? %llu 無符64位長整數%Lf 64位雙字四十二、常用GCD總結
為了方便地使用GCD,蘋果提供了一些方法方便我們將block放在主線程 或 后臺線程執行,或者延后執行。使用的例子如下:
// 后臺執行: dispatch_async(dispatch_get_global_queue(0, 0), ^{ // something }); // 主線程執行: dispatch_async(dispatch_get_main_queue(), ^{ // something }); // 一次性執行: static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ // code to be executed once }); // 延遲2秒執行: double delayInSeconds = 2.0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ // code to be executed on the main queue after delay }); dispatch_queue_t 也可以自己定義,如要要自定義queue,可以用dispatch_queue_create方法,示例如下:
dispatch_queue_t urls_queue = dispatch_queue_create("blog.devtang.com", NULL); dispatch_async(urls_queue, ^{ // your code }); dispatch_release(urls_queue); 另外,GCD還有一些高級用法,例如讓后臺2個線程并行執行,然后等2個線程都結束后,再匯總執行結果。這個可以用dispatch_group, dispatch_group_async 和 dispatch_group_notify來實現,示例如下:
dispatch_group_t group = dispatch_group_create(); dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{ // 并行執行的線程一 }); dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{ // 并行執行的線程二 }); dispatch_group_notify(group, dispatch_get_global_queue(0,0), ^{ // 上面的線程走完成后,最后通知走次block,保證這部分代碼最后執行 }); 四十三、 iOS中的隨機數
生成0-x之間的隨機正整數
int value =arc4random_uniform(x + 1);生成隨機正整數
int value = arc4random() 通過arc4random() 獲取0到x-1之間的整數的代碼如下:
int value = arc4random() % x; 獲取1到x之間的整數的代碼如下:
int value = (arc4random() % x) + 1; 最后如果想生成一個浮點數,可以在項目中定義如下宏:
#define ARC4RANDOM_MAX 0x100000000 然后就可以使用arc4random() 來獲取0到100之間浮點數了(精度是rand()的兩倍),代碼如下:
double val = floorf(((double)arc4random() / ARC4RANDOM_MAX) * 100.0f);四十四、系統自帶的UITableViewCell,其中cell.accessoryView可以自定義控件
if (indexPath.section == 2 && indexPath.row == 0) { cell.accessoryView = [[UISwitch alloc] init]; } else { cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; }四十五、isKindOfClass, isMemberOfClass的用法區分
-(BOOL) isKindOfClass: classObj判斷是否是這個類或者這個類的子類的實例 -(BOOL) isMemberOfClass: classObj 判斷是否是這個類的實例
實例一:
Person *person = [[Person alloc] init]; //父類 Teacher *teacher = [[Teacher alloc] init]; //子類 //YES if ([teacher isMemberOfClass:[Teacher class]]) { NSLog(@"teacher Teacher類的成員"); } //NO if ([teacher isMemberOfClass:[Person class]]) { NSLog(@"teacher Person類的成員"); } //NO if ([teacher isMemberOfClass:[NSObject class]]) { NSLog(@"teacher NSObject類的成員"); } 實例二:
Person *person = [[Person alloc] init]; Teacher *teacher = [[Teacher alloc] init]; //YES if ([teacher isKindOfClass:[Teacher class]]) { NSLog(@"teacher 是 Teacher類或Teacher的子類"); } //YES if ([teacher isKindOfClass:[Person class]]) { NSLog(@"teacher 是 Person類或Person的子類"); } //YES if ([teacher isKindOfClass:[NSObject class]]) { NSLog(@"teacher 是 NSObject類或NSObject的子類"); } isMemberOfClass判斷是否是屬于這類的實例,是否跟父類有關系他不管,所以isMemberOfClass指到父類時才會為NO;
四十六、關于UIScreen
UIScreen對象包含了整個屏幕的邊界矩形。當構造應用的用戶界面接口時,你應該使用該對象的屬性來獲得推薦的矩形大小,用以構造你的程序窗口。
CGRect bound = [[UIScreen mainScreen] bounds]; // 返回的是帶有狀態欄的Rect CGRect frame = [[UIScreen mainScreen] applicationFrame]; // 返回的是不帶有狀態欄的Rect float scale = [[UIScreen mainScreen] scale]; // 得到設備的自然分辨率
對于scale屬性需要做進一步的說明:
以前的iphone 設備屏幕分辨率都是320*480,后來apple 在iPhone 4中采用了名為Retina的顯示技術,iPhone 4采用了960x640像素分辨率的顯示屏幕。由于屏幕大小沒有變,還是3.5英寸,分辨率的提升將iPhone 4的顯示分辨率提升至iPhone 3GS的四倍,每英寸的面積里有326個像素。
scale屬性的值有兩個: scale = 1; 的時候是代表當前設備是320*480的分辨率(就是iphone4之前的設備) scale = 2; 的時候是代表分辨率為640*960的分辨率
// 判斷屏幕類型,普通還是視網膜 float scale = [[UIScreen mainScreen] scale]; if (scale == 1) { bIsRetina = NO; NSLog(@"普通屏幕"); }else if (scale == 2) { bIsRetina = YES; NSLog(@"視網膜屏幕"); }else{ NSLog(@"unknow screen mode !"); } 四十七、UIView的clipsTobounds屬性
view2添加view1到中,如果view2大于view1,或者view2的坐標不全在view1的范圍內,view2是蓋著view1的,意思就是超出的部份也會畫出來,UIView有一個屬性,clipsTobounds 默認情況下是NO。如果,我們想要view2把超出的那部份現實出來,就得改變它的父視圖也就view1的clipsTobounds屬性值。view1.clipsTobounds = YES; 可以很好地解決覆蓋的問題
四十八、百度坐標跟火星坐標相互轉換
//百度轉火星坐標+ (CLLocationCoordinate2D )bdToGGEncrypt:(CLLocationCoordinate2D)coord{ double x = coord.longitude - 0.0065, y = coord.latitude - 0.006; double z = sqrt(x * x + y * y) - 0.00002 * sin(y * M_PI); double theta = atan2(y, x) - 0.000003 * cos(x * M_PI); CLLocationCoordinate2D transformLocation ; transformLocation.longitude = z * cos(theta); transformLocation.latitude = z * sin(theta); return transformLocation;}//火星坐標轉百度坐標+ (CLLocationCoordinate2D )ggToBDEncrypt:(CLLocationCoordinate2D)coord{ double x = coord.longitude, y = coord.latitude; double z = sqrt(x * x + y * y) + 0.00002 * sin(y * M_PI); double theta = atan2(y, x) + 0.000003 * cos(x * M_PI); CLLocationCoordinate2D transformLocation ; transformLocation.longitude = z * cos(theta) + 0.0065; transformLocation.latitude = z * sin(theta) + 0.006; return transformLocation;}四十九、繪制1像素的線
#define SINGLE_LINE_WIDTH (1 / [UIScreen mainScreen].scale)#define SINGLE_LINE_ADJUST_OFFSET ((1 / [UIScreen mainScreen].scale) / 2)代碼如下:
UIView *view = [[UIView alloc] initWithFrame:CGrect(x - SINGLE_LINE_ADJUST_OFFSET, 0, SINGLE_LINE_WIDTH, 100)];注意:如果線寬為偶數Point的話,則不要去設置偏移,否則線條也會失真
五十、UILabel顯示HTML文本(IOS7以上)
NSString * htmlString = @"<html><body> Some html string /n <font size=/"13/" color=/"red/">This is some text!</font> </body></html>"; NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil]; UILabel * myLabel = [[UILabel alloc] initWithFrame:self.view.bounds]; myLabel.attributedText = attrStr; [self.view addSubview:myLabel];五十一、添加pch文件的步聚
1:創建新文件 ios->other->PCH file,創建一個pch文件:“工程名-Prefix.pch”:2:將building setting中的precompile header選項的路徑添加“$(SRCROOT)/項目名稱/pch文件名”(例如:$(SRCROOT)/LotteryFive/LotteryFive-Prefix.pch)3:將Precompile Prefix Header為YES,預編譯后的pch文件會被緩存起來,可以提高編譯速度五十二、兼容字體大小6plue跟它以下的區別
#define FONT_COMPATIBLE_SCREEN_OFFSET(_fontSize_) [UIFont systemFontOfSize:(_fontSize_ *([UIScreen mainScreen].scale) / 2)]在iPhone4~6中,縮放因子scale=2;在iPhone6+中,縮放因子scale=3運用時:myLabel.font=FONT_COMPATIBLE_SCREEN_OFFSET(15);五十三、APP虛擬器可以運行,在真機調試時報這個問題,因為把項目名稱設成中文導致
App installation failed There was an internal API error. Build Settings中的Packaging的Product Name設置成中文
五十四、關于Masonry
a:make.equalTo 或 make.greaterThanOrEqualTo (至多) 或 make.lessThanOrEqualTo(至少)make.left.greaterThanOrEqualTo(label);make.left.greaterThanOrEqualTo(label.mas_left);//width >= 200 && width <= 400make.width.greaterThanOrEqualTo(@200);make.width.lessThanOrEqualTo(@400)b:masequalTo 和 equalTo 區別:masequalTo 比equalTo多了類型轉換操作,一般來說,大多數時候兩個方法都是 通用的,但是對于數值元素使用mas_equalTo。對于對象或是多個屬性的處理,使用equalTo。特別是多個屬性時,必須使用equalToc:一些簡便賦值// make top = superview.top + 5, left = superview.left + 10,// bottom = superview.bottom - 15, right = superview.right - 20make.edges.equalTo(superview).insets(UIEdgeInsetsMake(5, 10, 15, 20))// make width and height greater than or equal to titleLabelmake.size.greaterThanOrEqualTo(titleLabel)// make width = superview.width + 100, height = superview.height - 50make.size.equalTo(superview).sizeOffset(CGSizeMake(100, -50))// make centerX = superview.centerX - 5, centerY = superview.centerY + 10make.center.equalTo(superview).centerOffset(CGPointMake(-5, 10))d:and關鍵字運用make.left.right.and.bottom.equalTo(superview); make.top.equalTo(otherView);e:優先;優先權(.priority,.priorityHigh,.priorityMedium,.priorityLow).priority允許您指定一個確切的優先級.priorityHigh 等價于UILayoutPriorityDefaultHigh.priorityMedium 介于高跟低之間.priorityLow 等價于UILayoutPriorityDefaultLow實例:make.left.greaterThanOrEqualTo(label.mas_left).with.priorityLow();make.top.equalTo(label.mas_top).with.priority(600);g:使用mas_makeConstraints創建constraint后,你可以使用局部變量或屬性來保存以便下次引用它;如果創建多個constraints,你可以采用數組來保存它們// 局部或者全局@property (nonatomic, strong) MASConstraint *topConstraint;// 創建約束并賦值[view1 mas_makeConstraints:^(MASConstraintMaker *make) { self.topConstraint = make.top.equalTo(superview.mas_top).with.offset(padding.top); make.left.equalTo(superview.mas_left).with.offset(padding.left);}];// 過后可以直接訪問self.topConstraint[self.topConstraint uninstall];h:mas_updateConstraints更新約束,有時你需要更新constraint(例如,動畫和調試)而不是創建固定constraint,可以使用mas_updateConstraints方法- (void)updateConstraints { [self.growingButton mas_updateConstraints:^(MASConstraintMaker *make) { make.center.equalTo(self); make.width.equalTo(@(self.buttonSize.width)).priorityLow(); make.height.equalTo(@(self.buttonSize.height)).priorityLow(); make.width.lessThanOrEqualTo(self); make.height.lessThanOrEqualTo(self); }]; //調用父updateConstraints [super updateConstraints];}i:mas_remakeConstraints更新約束,mas_remakeConstraints與mas_updateConstraints比較相似,都是更新constraint。不過,mas_remakeConstraints是刪除之前constraint,然后再添加新的constraint(適用于移動動畫);而mas_updateConstraints只是更新constraint的值。- (void)changeButtonPosition { [self.button mas_remakeConstraints:^(MASConstraintMaker *make) { make.size.equalTo(self.buttonSize); if (topLeft) { make.top.and.left.offset(10); } else { make.bottom.and.right.offset(-10); } }];}五十五、iOS中的round/roundf/ceil/ceilf/floor/floorf
round:如果參數是小數,則求本身的四舍五入。 ceil:如果參數是小數,則求最小的整數但不小于本身(向上取,ceil的英文意思有天花板的意思) floor:如果參數是小數,則求最大的整數但不大于本身(向下取,floor的英文意思有地板的意思)
Example:如果值是3.4的話,則 3.4 – round 3.000000 – ceil 4.000000 – floor 3.00000
五十六、中文輸入法的鍵盤上有聯想、推薦的功能,所以可能導致文本內容長度上有些不符合預期,導致越界
* Terminating app due to uncaught exception ‘NSRangeException’, reason: ‘NSMutableRLEArray replaceObjectsInRange:withObject:length:: Out of bounds’ 處理方式如下(textView.markedTextRange == nil)
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ if (textView.text.length >= self.textLengthLimit && text.length > range.length) { return NO; } return YES;}- (void)textViewDidChange:(UITextView *)textView{ self.placeholder.hidden = (self.textView.text.length > 0); if (textView.markedTextRange == nil && self.textLengthLimit > 0 && self.text.length > self.textLengthLimit) { textView.text = [textView.text substringToIndex:self.textLengthLimit]; }}五十七、關于導航欄透明度的設置及頂部布局起點位置設置
屬性:translucent
關閉
self.navigationController.navigationBar.translucent = NO;
開啟
self.navigationController.navigationBar.translucent = YES;
屬性:automaticallyAdjustsScrollViewInsets
當 automaticallyAdjustsScrollViewInsets 為 NO 時,tableview 是從屏幕的最上邊開始,也就是被 導航欄 & 狀態欄覆蓋
當 automaticallyAdjustsScrollViewInsets 為 YES 時,也是默認行為
五十八、UIScrollView偏移64問題
在一個VC里如果第一個控件是UIScrollView,注意是第一個控件,就是首先addsubview在VC.view上。接著加到scrollView上的View就會在Y點上發生64的偏移(也就是navigationBar的高度44+電池條的高度20)。 這個在iOS7以后才會出現。
解決辦法: self.automaticallyAdjustsScrollViewInsets = false; self是你當前那個VC。
如果這個scrollView不是第一個加到self.view上的。也不會發生64的偏移。
五十九、UIWebView在IOS9下底部出現黑邊解決方式
UIWebView底部的黑條很難看(在IOS8下不會,在IOS9會出現),特別是在底部還有透明控件的時候,隱藏的做法其實很簡單,只需要將opaque設為NO,背景色設為clearColor即可
六十、tabBarController跳轉到另一個一級頁面
當我們用tabBarController時,若已經到其中一個TabBar的子頁,又要跳轉到某一個一級的頁面時,如果這樣寫,導致底部出現黑邊,引起tabbar消失的bug
[self.navigationController popToRootViewControllerAnimated:YES];((AppDelegate *)AppDelegateInstance).tabBarController.selectedIndex = 2;解決方法一:刪除動畫
[self.navigationController popToRootViewControllerAnimated:NO];((AppDelegate *)AppDelegateInstance).tabBarController.selectedIndex = 2;解決方法二:延遲執行另一個系統操作
[self.navigationController popToRootViewControllerAnimated:NO]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{((AppDelegate *)AppDelegateInstance).tabBarController.selectedIndex = 2; });六十一、UIWebView獲取Html的標題title
titleLabel.text = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];六十二、漢字轉為拼音
- (NSString *)Charactor:(NSString *)aString getFirstCharactor:(BOOL)isGetFirst{ //轉成了可變字符串 NSMutableString *str = [NSMutableString stringWithString:aString]; //先轉換為帶聲調的拼音 CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO); //再轉換為不帶聲調的拼音 CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO); CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO); NSString *pinYin = [str capitalizedString]; //轉化為大寫拼音 if(isGetFirst) { //獲取并返回首字母 return [pinYin substringToIndex:1]; } else { return pinYin; }}六十三、屬性名以new開頭解決方式 因為new為OC關鍵詞,類似的還有alloc @property (nonatomic,copy) NSString *new_Passwd;
像上面這樣寫法會報錯,可以替換成
@property (nonatomic,copy,getter = theNewPasswd) NSString *new_Passwd;
六十四、去除編譯器警告
a:方法棄用告警
#pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" //會報警告的方法,比如SEL [TestFlight setDeviceIdentifier:[[UIDevice currentDevice] uniqueIdentifier]]; #pragma clang diagnostic pop b:未使用變量
#pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-variable" int a; #pragma clang diagnostic pop 六十五、self.navigationController.viewControllers修改 主要解決那些亂七八糟的跳轉邏輯,不按順序來的問題;
var controllerArr = self.navigationController?.viewControllers//獲取Controller數組controllerArr?.removeAll()//移除controllerArr中保存的歷史路徑 //重新添加新的路徑controllerArr?.append(self.navigationController?.viewControllers[0])controllerArr?.append(C)controllerArr?.append(B) //這時歷史路徑為(root -> c -> b) //將組建好的新的跳轉路徑 set進self.navigationController里self.navigationController?.setViewControllers(controllerArr!, animated: true)//直接寫入,完成跳轉B頁面的同時修改了之前的跳轉路徑
新聞熱點
疑難解答



















