引自:http://m.blog.csdn.net/article/details?id=52180380
記錄一些常用和不常用的iOS知識(shí)點(diǎn)呆万,防止遺忘丟失于游。(來(lái)源為收集自己項(xiàng)目中用到的或者整理看到博客中的知識(shí)點(diǎn)),如有錯(cuò)誤斜棚,歡迎大家批評(píng)指正;如有好的知識(shí)點(diǎn),也歡迎大家聯(lián)系我平项,添加上去。謝謝悍及!
一闽瓢、調(diào)用代碼使APP進(jìn)入后臺(tái),達(dá)到點(diǎn)擊Home鍵的效果心赶。(私有API)
[[UIApplication sharedApplication] performSelector:@selector(suspend)];
suspend的英文意思有:暫停; 懸; 掛; 延緩;
二扣讼、帶有中文的URL處理。(非UTF-8處理缨叫,注意一下)
大概舉個(gè)例子椭符,類似下面的URL,里面直接含有中文耻姥,可能導(dǎo)致播放不了销钝,那么我們要處理一個(gè)這個(gè)URL,因?yàn)樗俚傲擞缴粒尤挥弥形摹?/p>
http://static.tripbe.com/videofiles/視頻/我的自拍視頻.mp4
NSString *path? = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? (__bridge CFStringRef)model.mp4_url,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? CFSTR(""),? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
三曙搬、獲取UIWebView的高度
個(gè)人最常用的獲取方法,感覺這個(gè)比較靠譜
- (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設(shè)置圖片(UILabel一樣適用)
第一種方法:
利用的UIView的設(shè)置背景顏色方法纵装,用圖片做圖案顏色,然后傳給背景顏色据某。
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;
//設(shè)置顯示的圖片范圍
yourView.layer.contentsCenter = CGRectMake(0.25,0.25,0.5,0.5);//四個(gè)值在0-1之間橡娄,對(duì)應(yīng)的為x,y癣籽,width挽唉,height。
五筷狼、去掉UITableView多余的分割線
yourTableView.tableFooterView = [UIView new];
六瓶籽、調(diào)整cell分割線的位置,兩個(gè)方法一起用埂材,暴力解決塑顺,防脫發(fā)
-(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默認(rèn)為NO。那么如果你把這兩個(gè)類做為父試圖的話严拒,
里面的所有東東都不可以點(diǎn)擊哦扬绪。曾經(jīng)有一個(gè)人,讓我?guī)兔φ{(diào)試bug裤唠,他調(diào)試很久沒搞定挤牛,就是把WMPlayer對(duì)象(播放器對(duì)象)放到一個(gè)
UIImageView上面。這樣imageView addSubView:wmPlayer
后种蘸,播放器的任何東東都不能點(diǎn)擊了墓赴。userInteractionEabled設(shè)置為YES即可。
八航瞭、UISearchController和UISearchBar的Cancle按鈕改title問(wèn)題竣蹦,簡(jiǎn)單粗暴
- (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收起鍵盤何必這么麻煩
一個(gè)屬性搞定沧奴,效果好(UIScrollView同樣可以使用)
以前是不是覺得[self.view endEditing:YES];很屌痘括,這個(gè)下面的更屌。
yourTableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
另外一個(gè)枚舉為UIScrollViewKeyboardDismissModeInteractive滔吠,表示在鍵盤內(nèi)部滑動(dòng)纲菌,鍵盤逐漸下去。
十疮绷、NSTimer
1翰舌、NSTimer計(jì)算的時(shí)間并不精確
2、NSTimer需要添加到runLoop運(yùn)行才會(huì)執(zhí)行冬骚,但是這個(gè)runLoop的線程必須是已經(jīng)開啟椅贱。
3、NSTimer會(huì)對(duì)它的tagert進(jìn)行retain只冻,我們必須對(duì)其重復(fù)性的使用intvailte停止庇麦。target如果是self(指UIViewController),那么VC的retainCount+1喜德,如果你不釋放NSTimer山橄,那么你的VC就不會(huì)dealloc了,內(nèi)存泄漏了舍悯。
十一航棱、UIViewController沒用大小(frame)
經(jīng)常有人在群里問(wèn):怎么改變VC的大小啊萌衬?
瞬間無(wú)語(yǔ)饮醇。(只有UIView才能設(shè)置大小,VC是控制器啊秕豫,哥F蛹琛)
十二、用十六進(jìn)制獲取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的部分圓角問(wèn)題
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
//指定了需要成為圓角的角。該參數(shù)是UIRectCorner類型的沮脖,可選的值有:
* UIRectCornerTopLeft
* UIRectCornerTopRight
* UIRectCornerBottomLeft
* UIRectCornerBottomRight
* UIRectCornerAllCorners
從名字很容易看出來(lái)代表的意思金矛,使用“|”來(lái)組合就好了。
十五勺届、設(shè)置滑動(dòng)的時(shí)候隱藏navigationBar
navigationController.hidesBarsOnSwipe = Yes;
十六驶俊、iOS畫虛線
記得先 QuartzCore框架的導(dǎo)入
#import
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);
十七、自動(dòng)布局中多行UILabel免姿,需要設(shè)置其preferredMaxLayoutWidth屬性才能正常顯示多行內(nèi)容饼酿。另外如果出現(xiàn)顯示不全文本,可以在計(jì)算的結(jié)果基礎(chǔ)上+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;
十八故俐、? 禁止程序運(yùn)行時(shí)自動(dòng)鎖屏
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
十九、KVC相關(guān)紊婉,支持操作符
KVC同時(shí)還提供了很復(fù)雜的函數(shù)药版,主要有下面這些
①簡(jiǎn)單集合運(yùn)算符
簡(jiǎn)單集合運(yùn)算符共有@avg, @count 喻犁, @max 槽片, @min ,@sum5種肢础,都表示啥不用我說(shuō)了吧还栓, 目前還不支持自定義。
@interface Book : NSObject
@property (nonatomic,copy)? NSString* name;
@property (nonatomic,assign)? CGFloat price;
@end
@implementation Book
@end
Book *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-20 16:45:54.696 KVCDemo[1484:127089] sum:256.000000
2016-04-20 16:45:54.697 KVCDemo[1484:127089] avg:64.000000
2016-04-20 16:45:54.697 KVCDemo[1484:127089] count:4.000000
2016-04-20 16:45:54.697 KVCDemo[1484:127089] min:12.000000
NSArray 快速求總和 最大值 最小值 和 平均值
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時(shí)蝙云,盡量不要加到UIWindow上,加self.view上即可路召。如果加UIWindow上在iPad上勃刨,
旋轉(zhuǎn)屏幕的時(shí)候MBProgressHud不會(huì)旋轉(zhuǎn)。之前有人遇到這個(gè)bug股淡,我讓他改放到self.view上即可解決此bug身隐。
二十一、強(qiáng)制讓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];
//調(diào)整行間距
[attributedString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0, [self.contentLabel.text length])];
self.contentLabel.attributedText = attributedString;
二十三、CocoaPods pod install/pod update更新慢的問(wèn)題
pod install –verbose –no-repo-update
pod update –verbose –no-repo-update
如果不加后面的參數(shù),默認(rèn)會(huì)升級(jí)CocoaPods的spec倉(cāng)庫(kù),加一個(gè)參數(shù)可以省略這一步睹栖,然后速度就會(huì)提升不少期犬。
二十四、MRC和ARC混編設(shè)置方式
在XCode中targets的build phases選項(xiàng)下Compile Sources下選擇 不需要arc編譯的文件
雙擊輸入 -fno-objc-arc 即可
MRC工程中也可以使用ARC的類斑匪,方法如下:
在XCode中targets的build phases選項(xiàng)下Compile Sources下選擇要使用arc編譯的文件
雙擊輸入 -fobjc-arc 即可
二十五、把tableview里cell的小對(duì)勾的顏色改成別的顏色
_yourTableView.tintColor = [UIColor redColor];
二十六锋勺、解決同時(shí)按兩個(gè)按鈕進(jìn)兩個(gè)view的問(wèn)題
[button setExclusiveTouch:YES];
二十七蚀瘸、修改textFieldplaceholder字體顏色和大小
textField.placeholder = @"請(qǐng)輸入用戶名";
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
二十八、禁止textField和textView的復(fù)制粘貼菜單
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if ([UIMenuController sharedMenuController]) {
[UIMenuController sharedMenuController].menuVisible = NO;
}
return NO;
}
二十九:如何進(jìn)入我的軟件在app store 的頁(yè)面
先用iTunes Link Maker找到軟件在訪問(wèn)地址庶橱,格式為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就可以在瀏覽器中打開了∷照拢可以把這個(gè)地址放在自己的網(wǎng)站里寂嘉,鏈接到app store。
iTunes Link Maker地址:http://itunes.apple.com/linkmaker
三十枫绅、二級(jí)三級(jí)頁(yè)面隱藏系統(tǒng)tabbar
1垫释、單個(gè)處理
YourViewController *yourVC = [YourViewController new];
yourVC.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:yourVC animated:YES];
2.統(tǒng)一在基類里面處理
新建一個(gè)類BaseNavigationController繼承UINavigationController,然后重寫? -(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated這個(gè)方法撑瞧。所有的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;
}
}
三十一、取消系統(tǒng)的返回手勢(shì)
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
三十二预伺、修改UIWebView中字體的大小订咸,顏色
1、UIWebView設(shè)置字體大小酬诀,顏色脏嚷,字體:
UIWebView無(wú)法通過(guò)自身的屬性設(shè)置字體的一些屬性,只能通過(guò)html代碼進(jìn)行設(shè)置
在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];