iOS開發(fā)技巧
一、調(diào)用代碼使APP進(jìn)入后臺(tái),達(dá)到點(diǎn)擊Home鍵的效果。(私有API)
[[UIApplication sharedApplication] performSelector:@selector(suspend)];
suspend的英文意思有:暫停; 懸; 掛; 延緩;
二、帶有中文的URL處理。
大概舉個(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)試很久沒(méi)搞定,就是把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)存泄漏了。
十一、IOS編譯報(bào)錯(cuò):objc-class-ref in AppDelegate.o之解決方案 Xcode7
Undefined symbols for architecture x86_64:
"_OBJC_CLASS_$_QQApiInterface", referenced from:
objc-class-ref in AppDelegate.o
"_OBJC_CLASS_$_ShareSDK", referenced from:
objc-class-ref in AppDelegate.o
objc-class-ref in RecipeDetailViewController.o
objc-class-ref in showViewController.o
objc-class-ref in video_show.o
"_OBJC_CLASS_$_TencentOAuth", referenced from:
objc-class-ref in AppDelegate.o
"_OBJC_CLASS_$_WXApi", referenced from:
objc-class-ref in AppDelegate.o

1.把1.選中Targets—>Build Settings—>Architectures。
把build active architectures only 改為 NO。
2. 把最下面的Valid Architectures中的arm64參數(shù)刪掉就可以了
或者:
雙擊Architectures,選擇other,刪除$(ARCH_STANDARD),然后增加armv7和armv7s(寫上:$(ARCHS_STANDARD_32_BIT))。
3.clean 再build。
結(jié)果設(shè)置如下圖:

目前設(shè)置完成后,問(wèn)題順利解決,大家有更好的解決方案,歡迎討論!
十二、用十六進(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);
二十、系統(tǒng)和電池詳情
?- (void)viewDidLoad {
[super viewDidLoad];
[self showBatteryInfo];
[self showDeviceInfo];
// 檢測(cè)電池信息
[UIDevice currentDevice].batteryMonitoringEnabled = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showDeviceInfo) name:UIDeviceBatteryStateDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showBatteryInfo) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)showDeviceInfo
{
UIDevice *device = [UIDevice currentDevice];
NSString *msg = [NSString stringWithFormat:@"系統(tǒng)信息:\n模式:%@\n名字:%@\n系統(tǒng)名:%@\n系統(tǒng)的版本:%@",device.localizedModel,device.name,device.systemName,device.systemVersion];
NSLog(@"%@",msg);
self.systemInfoLabel.text = msg;
}
- (void)showBatteryInfo
{
UIDevice *device = [UIDevice currentDevice];
NSString *msg = [NSString stringWithFormat:@"電池的狀態(tài):%li\n電量:%.2f",(long)device.batteryState,device.batteryLevel];
NSLog(@"%@",msg);
self.batteryInfo.text = msg;
}
二十一、強(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ù)制粘貼菜單
這里有一個(gè)誤區(qū),很多同學(xué)直接使用UITextField,然后在VC里面寫這個(gè)方法,返回NO,沒(méi)效果。怎么搞都不行,但是如果用UIPasteboard的話,項(xiàng)目中所有的編輯框都不能復(fù)制黏貼了,真操蛋。
我們要做的是新建一個(gè)類MyTextField繼承UITextField,然后在MyTextField的.m文件里重寫這個(gè)方法,就可以單獨(dú)控制某個(gè)輸入框了。
-(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](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];
三十三、NSString處理技巧
使用場(chǎng)景舉例:可以用在處理用戶用戶輸入在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(對(duì)UI進(jìn)行更新只能在主線程進(jìn)行)
解釋:所謂的在主線程更新UI、操作UI,大致的意思就是設(shè)置UILabel的text或者設(shè)置tabbar的badgeValue,設(shè)置UIImageView的image等等。
回到主線程方式1:
[self performSelectorOnMainThread:@selector(updateImage:) withObject:data waitUntilDone:YES];
performSelectorOnMainThread方法是NSObject的分類方法,每個(gè)NSObject對(duì)象都有此方法,
它調(diào)用的selector方法是當(dāng)前調(diào)用控件的方法,例如使用UIImageView調(diào)用的時(shí)候selector就是UIImageView的方法
Object:代表調(diào)用方法的參數(shù),不過(guò)只能傳遞一個(gè)參數(shù)(如果有多個(gè)參數(shù)請(qǐng)使用對(duì)象進(jìn)行封裝)
waitUntilDone:是否線程任務(wù)完成執(zhí)行
回到主線程方式2:
dispatch_async(dispatch_get_main_queue(), ^{
//更新UI的代碼
});
這個(gè)不多解釋,GCD的方法,注意不要在主線程掉用。
三十五、判斷模擬器
if (TARGET_IPHONE_SIMULATOR) {
NSLog(@"是模擬器");
}else{
NSLog(@"不是模擬器");
}
三十六、真機(jī)測(cè)試報(bào) TCWeiboSDK 93 duplicate symbols for architecture armv7
這是因?yàn)樵陧?xiàng)目中引用的兩個(gè)相同的類庫(kù)引起了,在我的項(xiàng)目中是因?yàn)橐氲膬蓚€(gè)不同指令集引起的;
三十七、AFnetWorking報(bào)”Request failed: unacceptable
content-type: text/html”錯(cuò)誤
AFURLResponseSerialization.m文件設(shè)置
self.acceptableContentTypes = [NSSetsetWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
加上@”text/html”,部分,其實(shí)就是添加一種服務(wù)器返回的數(shù)據(jù)格式。
三十八、隱藏navigation跳轉(zhuǎn)后的返回按鈕
//隱藏頭部左邊的返回
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設(shè)置Section間距
在使用UITableViewStyleGrouped類型的UITableView的時(shí)候,經(jīng)常很奇怪的出現(xiàn)多余的section間距,那可能是因?yàn)槟阒辉O(shè)置了footer或者h(yuǎn)eader的間距中的其中一個(gè),那么另一個(gè)默認(rèn)為20個(gè)高度,只需要設(shè)置返回0.001的CGFlot的浮點(diǎn)數(shù)就可以解決這個(gè)多余的間距。
//Header底部間距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 40;//section頭部高度
}
//footer底部間距
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 0.001;
}
四十一、NSLog 輸出格式集合
? %@ 對(duì)象
? %d, %i 整數(shù)
? %u 無(wú)符整形
? %f 浮點(diǎn)/雙字
? %x, %X 二進(jìn)制整數(shù)
? %o 八進(jìn)制整數(shù)
? %zu size_t
? %p 指針
? %e 浮點(diǎn)/雙字 (科學(xué)計(jì)算)
? %g 浮點(diǎn)/雙字
? %s C 字符串
? %.*s Pascal字符串
? %c 字符
? %C unichar
? %lld 64位長(zhǎng)整數(shù)(long long)
? %llu 無(wú)符64位長(zhǎng)整數(shù)
%Lf 64位雙字
四十二、常用GCD總結(jié)
為了方便地使用GCD,蘋果提供了一些方法方便我們將block放在主線程 或 后臺(tái)線程執(zhí)行,或者延后執(zhí)行。使用的例子如下:
// 后臺(tái)執(zhí)行:
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// something
});
// 主線程執(zhí)行:
dispatch_async(dispatch_get_main_queue(), ^{
// something
});
// 一次性執(zhí)行:
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// code to be executed once
});
// 延遲2秒執(zhí)行:
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還有一些高級(jí)用法,例如讓后臺(tái)2個(gè)線程并行執(zhí)行,然后等2個(gè)線程都結(jié)束后,再匯總執(zhí)行結(jié)果。這個(gè)可以用dispatch_group, dispatch_group_async 和 dispatch_group_notify來(lái)實(shí)現(xiàn),示例如下:
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{
// 并行執(zhí)行的線程一
});
dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{
// 并行執(zhí)行的線程二
});
dispatch_group_notify(group, dispatch_get_global_queue(0,0), ^{
// 上面的線程走完成后,最后通知走次block,保證這部分代碼最后執(zhí)行
});
四十三、 iOS中的隨機(jī)數(shù)
生成0-x之間的隨機(jī)正整數(shù)
int value =arc4random_uniform(x + 1);
生成隨機(jī)正整數(shù)
int value = arc4random()
通過(guò)arc4random() 獲取0到x-1之間的整數(shù)的代碼如下:
int value = arc4random() % x;
獲取1到x之間的整數(shù)的代碼如下:
int value = (arc4random() % x) + 1;
最后如果想生成一個(gè)浮點(diǎn)數(shù),可以在項(xiàng)目中定義如下宏:
#define ARC4RANDOM_MAX 0x100000000
然后就可以使用arc4random() 來(lái)獲取0到100之間浮點(diǎn)數(shù)了(精度是rand()的兩倍),代碼如下:
double val = floorf(((double)arc4random() / ARC4RANDOM_MAX) * 100.0f);
四十四、系統(tǒng)自帶的UITableViewCell,其中cell.accessoryView可以自定義控件
if (indexPath.section == 2 && indexPath.row == 0) {
cell.accessoryView = [[UISwitch alloc] init];
} else {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
四十五、isKindOfClass, isMemberOfClass的用法區(qū)分
-(BOOL) isKindOfClass: classObj判斷是否是這個(gè)類或者這個(gè)類的子類的實(shí)例
-(BOOL) isMemberOfClass: classObj 判斷是否是這個(gè)類的實(shí)例
實(shí)例一:
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類的成員");
}
實(shí)例二:
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判斷是否是屬于這類的實(shí)例,是否跟父類有關(guān)系他不管,所以isMemberOfClass指到父類時(shí)才會(huì)為NO;
四十六、關(guān)于UIScreen
UIScreen對(duì)象包含了整個(gè)屏幕的邊界矩形。當(dāng)構(gòu)造應(yīng)用的用戶界面接口時(shí),你應(yīng)該使用該對(duì)象的屬性來(lái)獲得推薦的矩形大小,用以構(gòu)造你的程序窗口。
CGRect bound = [[UIScreen mainScreen] bounds]; // 返回的是帶有狀態(tài)欄的Rect
CGRect frame = [[UIScreen mainScreen] applicationFrame]; // 返回的是不帶有狀態(tài)欄的Rect
float scale = [[UIScreen mainScreen] scale]; // 得到設(shè)備的自然分辨率
對(duì)于scale屬性需要做進(jìn)一步的說(shuō)明:
以前的iphone 設(shè)備屏幕分辨率都是320*480,后來(lái)apple 在iPhone 4中采用了名為Retina的顯示技術(shù),iPhone
4采用了960x640像素分辨率的顯示屏幕。由于屏幕大小沒(méi)有變,還是3.5英寸,分辨率的提升將iPhone 4的顯示分辨率提升至iPhone
3GS的四倍,每英寸的面積里有326個(gè)像素。
scale屬性的值有兩個(gè):
scale = 1; 的時(shí)候是代表當(dāng)前設(shè)備是320*480的分辨率(就是iphone4之前的設(shè)備)
scale = 2; 的時(shí)候是代表分辨率為640*960的分辨率
// 判斷屏幕類型,普通還是視網(wǎng)膜
float scale = [[UIScreen mainScreen] scale];
if (scale == 1) {
bIsRetina = NO;
NSLog(@"普通屏幕");
}else if (scale == 2) {
bIsRetina = YES;
NSLog(@"視網(wǎng)膜屏幕");
}else{
NSLog(@"unknow screen mode !");
}
四十七、UIView的clipsTobounds屬性
view2添加view1到中,如果view2大于view1,或者view2的坐標(biāo)不全在view1的范圍內(nèi),view2是蓋著view1的,意思就是超出的部份也會(huì)畫出來(lái),UIView有一個(gè)屬性,clipsTobounds 默認(rèn)情況下是NO。如果,我們想要view2把超出的那部份現(xiàn)實(shí)出來(lái),就得改變它的父視圖也就view1的clipsTobounds屬性值。view1.clipsTobounds = YES;
可以很好地解決覆蓋的問(wèn)題
四十八、百度坐標(biāo)跟火星坐標(biāo)相互轉(zhuǎn)換
//百度轉(zhuǎn)火星坐標(biāo)
+ (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;
}
//火星坐標(biāo)轉(zhuǎn)百度坐標(biāo)
+ (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)];
注意:如果線寬為偶數(shù)Point的話,則不要去設(shè)置偏移,否則線條也會(huì)失真
五十、UILabel顯示HTML文本(IOS7以上)
NSString * htmlString = @" Some html string \n This is some text! ";
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:創(chuàng)建新文件 ios->other->PCH file,創(chuàng)建一個(gè)pch文件:“工程名-Prefix.pch”:
2:將building setting中的precompile header選項(xiàng)的路徑添加“$(SRCROOT)/項(xiàng)目名稱/pch文件名”(例如:$(SRCROOT)/LotteryFive/LotteryFive-Prefix.pch)
3:將Precompile Prefix Header為YES,預(yù)編譯后的pch文件會(huì)被緩存起來(lái),可以提高編譯速度
五十二、兼容字體大小6plue跟它以下的區(qū)別
#define FONT_COMPATIBLE_SCREEN_OFFSET(_fontSize_) [UIFont systemFontOfSize:(_fontSize_ *([UIScreen mainScreen].scale) / 2)]
在iPhone4~6中,縮放因子scale=2;在iPhone6+中,縮放因子scale=3
運(yùn)用時(shí):
myLabel.font=FONT_COMPATIBLE_SCREEN_OFFSET(15);
五十三、APP虛擬器可以運(yùn)行,在真機(jī)調(diào)試時(shí)報(bào)這個(gè)問(wèn)題,因?yàn)榘秧?xiàng)目名稱設(shè)成中文導(dǎo)致
App installation failed
There was an internal API error.
Build Settings中的Packaging的Product Name設(shè)置成中文
五十四、關(guān)于Masonry
a:make.equalTo 或 make.greaterThanOrEqualTo (至多) 或 make.lessThanOrEqualTo(至少)
make.left.greaterThanOrEqualTo(label);
make.left.greaterThanOrEqualTo(label.mas_left);
//width >= 200 && width <= 400
make.width.greaterThanOrEqualTo(@200);
make.width.lessThanOrEqualTo(@400)
b:masequalTo 和 equalTo 區(qū)別:masequalTo 比equalTo多了類型轉(zhuǎn)換操作,一般來(lái)說(shuō),大多數(shù)時(shí)候兩個(gè)方法都是 通用的,但是對(duì)于數(shù)值元素使用mas_equalTo。對(duì)于對(duì)象或是多個(gè)屬性的處理,使用equalTo。特別是多個(gè)屬性時(shí),必須使用equalTo
c:一些簡(jiǎn)便賦值
// make top = superview.top + 5, left = superview.left + 10,
// bottom = superview.bottom - 15, right = superview.right - 20
make.edges.equalTo(superview).insets(UIEdgeInsetsMake(5, 10, 15, 20))
// make width and height greater than or equal to titleLabel
make.size.greaterThanOrEqualTo(titleLabel)
// make width = superview.width + 100, height = superview.height - 50
make.size.equalTo(superview).sizeOffset(CGSizeMake(100, -50))
// make centerX = superview.centerX - 5, centerY = superview.centerY + 10
make.center.equalTo(superview).centerOffset(CGPointMake(-5, 10))
d:and關(guān)鍵字運(yùn)用
make.left.right.and.bottom.equalTo(superview);
make.top.equalTo(otherView);
e:優(yōu)先;優(yōu)先權(quán)(.priority,.priorityHigh,.priorityMedium,.priorityLow)
.priority允許您指定一個(gè)確切的優(yōu)先級(jí)
.priorityHigh 等價(jià)于UILayoutPriorityDefaultHigh
.priorityMedium 介于高跟低之間
.priorityLow 等價(jià)于UILayoutPriorityDefaultLow
實(shí)例:
make.left.greaterThanOrEqualTo(label.mas_left).with.priorityLow();
make.top.equalTo(label.mas_top).with.priority(600);
g:使用mas_makeConstraints創(chuàng)建constraint后,你可以使用局部變量或?qū)傩詠?lái)保存以便下次引用它;如果創(chuàng)建多個(gè)constraints,你可以采用數(shù)組來(lái)保存它們
// 局部或者全局
@property (nonatomic, strong) MASConstraint *topConstraint;
// 創(chuàng)建約束并賦值
[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);
}];
// 過(guò)后可以直接訪問(wèn)self.topConstraint
[self.topConstraint uninstall];
h:mas_updateConstraints更新約束,有時(shí)你需要更新constraint(例如,動(dòng)畫和調(diào)試)而不是創(chuàng)建固定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);
}];
//調(diào)用父updateConstraints
[super updateConstraints];
}
i:mas_remakeConstraints更新約束,mas_remakeConstraints與mas_updateConstraints比較相似,都是更新constraint。不過(guò),mas_remakeConstraints是刪除之前constraint,然后再添加新的constraint(適用于移動(dòng)動(dòng)畫);而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:如果參數(shù)是小數(shù),則求本身的四舍五入。
ceil:如果參數(shù)是小數(shù),則求最小的整數(shù)但不小于本身(向上取,ceil的英文意思有天花板的意思)
floor:如果參數(shù)是小數(shù),則求最大的整數(shù)但不大于本身(向下取,floor的英文意思有地板的意思)
Example:如果值是3.4的話,則
3.4 – round 3.000000
– ceil 4.000000
– floor 3.00000
五十六、中文輸入法的鍵盤上有聯(lián)想、推薦的功能,所以可能導(dǎo)致文本內(nèi)容長(zhǎng)度上有些不符合預(yù)期,導(dǎo)致越界
***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];
}
}
五十七、關(guān)于導(dǎo)航欄透明度的設(shè)置及頂部布局起點(diǎn)位置設(shè)置
屬性:translucent
關(guān)閉
self.navigationController.navigationBar.translucent = NO;
開啟
self.navigationController.navigationBar.translucent = YES;
屬性:automaticallyAdjustsScrollViewInsets
當(dāng) automaticallyAdjustsScrollViewInsets 為 NO 時(shí),tableview 是從屏幕的最上邊開始,也就是被 導(dǎo)航欄 & 狀態(tài)欄覆蓋
當(dāng) automaticallyAdjustsScrollViewInsets 為 YES 時(shí),也是默認(rèn)行為
五十八、UIScrollView偏移64問(wèn)題
在一個(gè)VC里如果第一個(gè)控件是UIScrollView,注意是第一個(gè)控件,就是首先addsubview在VC.view上。接著加到scrollView上的View就會(huì)在Y點(diǎn)上發(fā)生64的偏移(也就是navigationBar的高度44+電池條的高度20)。
這個(gè)在iOS7以后才會(huì)出現(xiàn)。
解決辦法:
self.automaticallyAdjustsScrollViewInsets = false; self是你當(dāng)前那個(gè)VC。
如果這個(gè)scrollView不是第一個(gè)加到self.view上的。也不會(huì)發(fā)生64的偏移。
五十九、UIWebView在IOS9下底部出現(xiàn)黑邊解決方式
UIWebView底部的黑條很難看(在IOS8下不會(huì),在IOS9會(huì)出現(xiàn)),特別是在底部還有透明控件的時(shí)候,隱藏的做法其實(shí)很簡(jiǎn)單,只需要將opaque設(shè)為NO,背景色設(shè)為clearColor即可
六十、tabBarController跳轉(zhuǎn)到另一個(gè)一級(jí)頁(yè)面
當(dāng)我們用tabBarController時(shí),若已經(jīng)到其中一個(gè)TabBar的子頁(yè),又要跳轉(zhuǎn)到某一個(gè)一級(jí)的頁(yè)面時(shí),如果這樣寫,導(dǎo)致底部出現(xiàn)黑邊,引起tabbar消失的bug
[self.navigationController popToRootViewControllerAnimated:YES];
((AppDelegate *)AppDelegateInstance).tabBarController.selectedIndex = 2;
解決方法一:刪除動(dòng)畫
[self.navigationController popToRootViewControllerAnimated:NO];
((AppDelegate *)AppDelegateInstance).tabBarController.selectedIndex = 2;
解決方法二:延遲執(zhí)行另一個(gè)系統(tǒng)操作
[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的標(biāo)題title
titleLabel.text = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
六十二、漢字轉(zhuǎn)為拼音
- (NSString *)Charactor:(NSString *)aString getFirstCharactor:(BOOL)isGetFirst
{
//轉(zhuǎn)成了可變字符串
NSMutableString *str = [NSMutableString stringWithString:aString];
//先轉(zhuǎn)換為帶聲調(diào)的拼音
CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
//再轉(zhuǎn)換為不帶聲調(diào)的拼音
CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
NSString *pinYin = [str capitalizedString];
//轉(zhuǎn)化為大寫拼音
if(isGetFirst)
{
//獲取并返回首字母
return [pinYin substringToIndex:1];
}
else
{
return pinYin;
}
}
六十三、屬性名以new開頭解決方式
因?yàn)閚ew為OC關(guān)鍵詞,類似的還有alloc
@property (nonatomic,copy) NSString *new_Passwd;
像上面這樣寫法會(huì)報(bào)錯(cuò),可以替換成
@property (nonatomic,copy,getter = theNewPasswd) NSString *new_Passwd;
六十四、去除編譯器警告
a:方法棄用告警
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
//會(huì)報(bào)警告的方法,比如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修改
主要解決那些亂七八糟的跳轉(zhuǎn)邏輯,不按順序來(lái)的問(wèn)題;
var controllerArr = self.navigationController?.viewControllers//獲取Controller數(shù)組
controllerArr?.removeAll()//移除controllerArr中保存的歷史路徑
//重新添加新的路徑
controllerArr?.append(self.navigationController?.viewControllers[0])
controllerArr?.append(C)
controllerArr?.append(B)
//這時(shí)歷史路徑為(root -> c -> b)
//將組建好的新的跳轉(zhuǎn)路徑 set進(jìn)self.navigationController里
self.navigationController?.setViewControllers(controllerArr!, animated: true)
//直接寫入,完成跳轉(zhuǎn)B頁(yè)面的同時(shí)修改了之前的跳轉(zhuǎn)路徑