一幽纷、調(diào)用代碼使APP進(jìn)入后臺缕碎,達(dá)到點(diǎn)擊Home鍵的效果乙嘀。
[[UIApplication sharedApplication]performSelector:@selector(suspend)];
1
suspend的英文意思有:暫停; 懸; 掛; 延緩;
二恃疯、帶有中文的URL處理殴胧。(非UTF-8處理委造,注意一下)
大概舉個例子戳鹅,類似下面的URL,里面直接含有中文昏兆,可能導(dǎo)致播放不了枫虏,那么我們要處理一個這個URL,因為他太操蛋了,居然用中文隶债。
http://static.tripbe.com/videofiles/視頻/我的自拍視頻.mp4NSString *path? = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? (__bridge CFStringRef)model.mp4_url,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? CFSTR(""),? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
1
2
三腾它、獲取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);? }
1
2
3
4
5
四死讹、給UIView設(shè)置圖片(UILabel一樣適用)
第一種方法:
利用的UIView的設(shè)置背景顏色方法瞒滴,用圖片做圖案顏色,然后傳給背景顏色赞警。
UIColor*bgColor = [UIColorcolorWithPatternImage: [UIImageimageNamed:@"bgImg.png"];UIView*myView = [[UIViewalloc] initWithFrame:CGRectMake(0,0,320,480)];[myView setBackGroundColor:bgColor];
1
2
3
第二種方法:
UIImage*image = [UIImageimageNamed:@"yourPicName@2x.png"];yourView.layer.contents= (__bridgeid)image.CGImage;//設(shè)置顯示的圖片范圍yourView.layer.contentsCenter= CGRectMake(0.25,0.25,0.5,0.5);//四個值在0-1之間妓忍,對應(yīng)的為x,y愧旦,width世剖,height
1
2
3
4
五、去掉UITableView多余的分割線
yourTableView.tableFooterView = [UIView new];
1
六笤虫、調(diào)整cell分割線的位置搁廓,兩個方法一起用,暴力解決耕皮,防脫發(fā)
-(void)viewDidLayoutSubviews {if([self.mytableviewrespondsToSelector:@selector(setSeparatorInset:)]) {? ? ? ? [self.mytableviewsetSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];? ? }if([self.mytableviewrespondsToSelector:@selector(setLayoutMargins:)])? {? ? ? ? [self.mytableviewsetLayoutMargins: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默認(rèn)為NO。那么如果你把這兩個類做為父試圖的話凌停,里面的所有東東都不可以點(diǎn)擊哦粱年。曾經(jīng)有一個人,讓我?guī)兔φ{(diào)試bug罚拟,他調(diào)試很久沒搞定台诗,就是把WMPlayer對象(播放器對象)放到一個UIImageView上面。這樣imageView
addSubView:wmPlayer 后赐俗,播放器的任何東東都不能點(diǎn)擊了拉队。userInteractionEabled設(shè)置為YES即可。
八阻逮、UISearchController和UISearchBar的Cancle按鈕改title問題粱快,簡單粗暴
- (BOOL)searchBarShouldBeginEditing:(UISearchBar*)searchBar{? ? searchController.searchBar.showsCancelButton=YES;UIButton*canceLBtn = [searchController.searchBarvalueForKey:@"cancelButton"];? ? [canceLBtn setTitle:@"取消"forState:UIControlStateNormal];? ? [canceLBtn setTitleColor:[UIColorcolorWithRed:14.0/255.0green:180.0/255.0blue:0.0/255.0alpha:1.00] forState:UIControlStateNormal];? ? searchBar.showsCancelButton=YES;returnYES;}
九、UITableView收起鍵盤何必這么麻煩
一個屬性搞定叔扼,效果好(UIScrollView同樣可以使用)
以前是不是覺得[self.view endEditing:YES];很屌事哭,這個下面的更屌。
yourTableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
另外一個枚舉為UIScrollViewKeyboardDismissModeInteractive瓜富,表示在鍵盤內(nèi)部滑動鳍咱,鍵盤逐漸下去。
十与柑、NSTimer
1谤辜、NSTimer計算的時間并不精確
2蓄坏、NSTimer需要添加到runLoop運(yùn)行才會執(zhí)行,但是這個runLoop的線程必須是已經(jīng)開啟丑念。
3涡戳、NSTimer會對它的tagert進(jìn)行retain,我們必須對其重復(fù)性的使用intvailte停止渠欺。target如果是self(指UIViewController),那么VC的retainCount+1椎眯,如果你不釋放NSTimer挠将,那么你的VC就不會dealloc了,內(nèi)存泄漏了编整。
十一舔稀、UIViewController沒用大小(frame)
經(jīng)常有人在群里問:怎么改變VC的大小啊掌测?
瞬間無語内贮。(只有UIView才能設(shè)置大小,VC是控制器啊汞斧,哥R褂簟)
十二、用十六進(jìn)制獲取UIColor(類方法或者Category都可以粘勒,這里我用工具類方法)
+ (UIColor*)colorWithHexString:(NSString*)color{NSString*cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];// String should be 6 or 8 charactersif([cString length] <6) {return[UIColorclearColor];? ? }// strip 0X if it appearsif([cString hasPrefix:@"0X"])? ? ? ? cString = [cString substringFromIndex:2];if([cString hasPrefix:@"#"])? ? ? ? cString = [cString substringFromIndex:1];if([cString length] !=6)return[UIColorclearColor];// Separate into r, g, b substringsNSRangerange;? ? range.location=0;? ? range.length=2;//rNSString*rString = [cString substringWithRange:range];//grange.location=2;NSString*gString = [cString substringWithRange:range];//brange.location=4;NSString*bString = [cString substringWithRange:range];// Scan valuesunsignedintr, g, b;? ? [[NSScanner scannerWithString:rString] scanHexInt:&r];? ? [[NSScanner scannerWithString:gString] scanHexInt:&g];? ? [[NSScanner scannerWithString:bString] scanHexInt:&b];return[UIColorcolorWithRed:((float) r /255.0f) green:((float) g /255.0f) blue:((float) b /255.0f) alpha:1.0f];}
十三竞端、獲取今天是星期幾
+ (NSString*) getweekDayStringWithDate:(NSDate*) date{NSCalendar* calendar = [[NSCalendaralloc] initWithCalendarIdentifier:NSGregorianCalendar];// 指定日歷的算法NSDateComponents *comps = [calendar components:NSWeekdayCalendarUnit fromDate:date];// 1 是周日,2是周一 3.以此類推NSNumber* weekNumber = @([comps weekday]);NSIntegerweekInt = [weekNumber integerValue];NSString*weekDayString = @"(周一)";switch(weekInt) {case1:? ? ? ? {? ? ? ? ? ? weekDayString = @"(周日)";? ? ? ? }break;case2:? ? ? ? {? ? ? ? ? ? weekDayString = @"(周一)";? ? ? ? }break;case3:? ? ? ? {? ? ? ? ? ? weekDayString = @"(周二)";? ? ? ? }break;case4:? ? ? ? {? ? ? ? ? ? weekDayString = @"(周三)";? ? ? ? }break;case5:? ? ? ? {? ? ? ? ? ? weekDayString = @"(周四)";? ? ? ? }break;case6:? ? ? ? {? ? ? ? ? ? weekDayString = @"(周五)";? ? ? ? }break;case7:? ? ? ? {? ? ? ? ? ? weekDayString = @"(周六)";? ? ? ? }break;default:break;? ? }returnweekDayString;}
十四庙睡、UIView的部分圓角問題
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(120,10,80,80)];view2.backgroundColor= [UIColor redColor];[self.viewaddSubview:view2];UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view2.boundsbyRoundingCorners: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//指定了需要成為圓角的角。該參數(shù)是UIRectCorner類型的乘陪,可選的值有:* UIRectCornerTopLeft* UIRectCornerTopRight* UIRectCornerBottomLeft* UIRectCornerBottomRight* UIRectCornerAllCorners
從名字很容易看出來代表的意思统台,使用“|”來組合就好了。
十五啡邑、設(shè)置滑動的時候隱藏navigationBar
navigationController.hidesBarsOnSwipe = Yes;
1
十六贱勃、iOS畫虛線
記得先 QuartzCore框架的導(dǎo)入
#importCGContextRef context =UIGraphicsGetCurrentContext();? CGContextBeginPath(context);? CGContextSetLineWidth(context,2.0);? CGContextSetStrokeColorWithColor(context, [UIColorwhiteColor].CGColor);CGFloatlengths[] = {10,10};? CGContextSetLineDash(context,0, lengths,2);? CGContextMoveToPoint(context,10.0,20.0);? CGContextAddLineToPoint(context,310.0,20.0);? CGContextStrokePath(context);? CGContextClosePath(context);
十七、自動布局中多行UILabel谤逼,需要設(shè)置其preferredMaxLayoutWidth屬性才能正常顯示多行內(nèi)容募寨。另外如果出現(xiàn)顯示不全文本,可以在計算的結(jié)果基礎(chǔ)上+0.5森缠。
CGFloat h = [model.messageboundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width- kGAP-kAvatar_Size -2*kGAP, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.height+0.5;
十八拔鹰、 禁止程序運(yùn)行時自動鎖屏
[[UIApplication sharedApplication]setIdleTimerDisabled:YES];
十九、KVC相關(guān)贵涵,支持操作符
KVC同時還提供了很復(fù)雜的函數(shù)列肢,主要有下面這些
①簡單集合運(yùn)算符
簡單集合運(yùn)算符共有@avg恰画, @count , @max 瓷马, @min 拴还,@sum5種,都表示啥不用我說了吧欧聘, 目前還不支持自定義片林。
@interfaceBook:NSObject@property(nonatomic,copy)NSString* name;@property(nonatomic,assign)CGFloatprice;@end@implementationBook@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);打印結(jié)果2016-04-2016:45:54.696KVCDemo[1484:127089] sum:256.0000002016-04-2016:45:54.697KVCDemo[1484:127089] avg:64.0000002016-04-2016:45:54.697KVCDemo[1484:127089] count:4.0000002016-04-2016:45:54.697KVCDemo[1484:127089] min:12.000000
NSArray 快速求總和 最大值 最小值 和 平均值
NSArray*array = [NSArrayarrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10",nil];CGFloatsum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];CGFloatavg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];CGFloatmax =[[array valueForKeyPath:@"@max.floatValue"] floatValue];CGFloatmin =[[array valueForKeyPath:@"@min.floatValue"] floatValue];NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);
二十、使用MBProgressHud時怀骤,盡量不要加到UIWindow上费封,加self.view上即可。如果加UIWindow上在iPad上蒋伦,旋轉(zhuǎn)屏幕的時候MBProgressHud不會旋轉(zhuǎn)弓摘。之前有人遇到這個bug,我讓他改放到self.view上即可解決此bug痕届。
二十一韧献、強(qiáng)制讓App直接退出(非閃退,非崩潰)
- (void)exitApplication {? ? ? ? AppDelegate *app = [UIApplicationsharedApplication].delegate;UIWindow*window = app.window;? ? ? ? [UIViewanimateWithDuration:1.0f animations:^{? ? ? ? ? ? window.alpha=0;? ? ? ? } completion:^(BOOLfinished) {? ? ? ? ? ? exit(0);? ? ? ? }];? ? }
二十二研叫、Label行間距
NSMutableAttributedString *attributedString =? ? ? [[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];NSMutableParagraphStyle *paragraphStyle =? [[NSMutableParagraphStyle alloc] init];? [paragraphStyle setLineSpacing:3];//調(diào)整行間距? ? ? ? ? [attributedString addAttribute:NSParagraphStyleAttributeName? ? ? ? ? ? ? ? ? ? ? ? ? value:paragraphStyle? ? ? ? ? ? ? ? ? ? ? ? ? range:NSMakeRange(0, [self.contentLabel.textlength])];self.contentLabel.attributedText= attributedString;
二十三锤窑、CocoaPods pod install/pod update更新慢的問題
pod install –verbose –no-repo-update
pod update –verbose –no-repo-update
如果不加后面的參數(shù),默認(rèn)會升級CocoaPods的spec倉庫嚷炉,加一個參數(shù)可以省略這一步果复,然后速度就會提升不少。
二十四渤昌、MRC和ARC混編設(shè)置方式
在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];
二十六独柑、解決同時按兩個按鈕進(jìn)兩個view的問題
[button setExclusiveTouch:YES];
二十七迈窟、修改textFieldplaceholder字體顏色和大小
textField.placeholder = @"請輸入用戶名";? [textFieldsetValue:[UIColor redColor]forKeyPath:@"_placeholderLabel.textColor"];? [textFieldsetValue:[UIFont boldSystemFontOfSize:16]forKeyPath:@"_placeholderLabel.font"];
1
2
3
二十八、禁止textField和textView的復(fù)制粘貼菜單
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{if([UIMenuController sharedMenuController]) {? ? ? [UIMenuController sharedMenuController].menuVisible=NO;? ? }returnNO;}
**二十九:如何進(jìn)入我的軟件在app store 的頁面
先用iTunes Link Maker找到軟件在訪問地址忌栅,格式為itms-apps://ax.itunes.apple.com/…车酣,然后**
#define? ITUNESLINK? @"itms-apps://ax.itunes.apple.com/..."NSURL*url = [NSURLURLWithString:ITUNESLINK];if([[UIApplicationsharedApplication] canOpenURL:url]){? ? [[UIApplicationsharedApplication] openURL:url];}
三十、二級三級頁面隱藏系統(tǒng)tabba
1索绪、單個處理
YourViewController *yourVC = [YourViewController new];yourVC.hidesBottomBarWhenPushed=YES;[self.navigationControllerpushViewController:yourVC animated:YES]
2.統(tǒng)一在基類里面處理
新建一個類BaseNavigationController繼承UINavigationController湖员,然后重寫 -(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated這個方法。所有的push事件都走此方法瑞驱。
@interfaceBaseNavigationController:UINavigationController@end-(void)pushViewController:(UIViewController*)viewController animated:(BOOL)animated{? ? ? ? [superpushViewController:viewController animated:animated];if(self.viewControllers.count>1) {? ? ? ? ? ? viewController.hidesBottomBarWhenPushed=YES;? ? ? ? }? ? }
三十一娘摔、取消系統(tǒng)的返回手勢
self.navigationController.interactivePopGestureRecognizer.enabled= NO;
1
三十二、修改UIWebView中字體的大小唤反,顏色
1凳寺、UIWebView設(shè)置字體大小鸭津,顏色,字體:
UIWebView無法通過自身的屬性設(shè)置字體的一些屬性肠缨,只能通過html代碼進(jìn)行設(shè)置
在webView加載完畢后逆趋,在
- (void)webViewDidFinishLoad:(UIWebView *)webView方法中加入js代碼? ? ? NSString *str= @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '60%'";? ? ? [_webView stringByEvaluatingJavaScriptFromString:str];
或者加入以下代碼
NSString*jsString = [[NSStringalloc] initWithFormat:@"document.body.style.fontSize=%f;document.body.style.color=%@",fontSize,fontColor];? ? ? ? ? [webView stringByEvaluatingJavaScriptFromString:jsString];
1
2
三十三、移除所有子視圖晒奕,無需循環(huán)只需要一句代碼?
[view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];