在iOS開(kāi)發(fā)中經(jīng)常需要使用的或不常用的知識(shí)點(diǎn)的總結(jié),幾年的收藏和積累(踩過(guò)的坑)。
一、 iPhone Size

二、 給navigation Bar 設(shè)置 title 顏色
UIColor?*whiteColor?=?[UIColor?whiteColor];
NSDictionary?*dic?=?[NSDictionary?dictionaryWithObject:whiteColor?forKey:NSForegroundColorAttributeName];
[self.navigationController.navigationBar?setTitleTextAttributes:dic];
三、 如何把一個(gè)CGPoint存入數(shù)組里
CGPoint??itemSprite1position?=?CGPointMake(100,?200);
NSMutableArray?*?array??=?[[NSMutableArray?alloc]?initWithObjects:NSStringFromCGPoint(itemSprite1position),nil];
//????從數(shù)組中取值的過(guò)程是這樣的:
CGPoint?point?=?CGPointFromString([array?objectAtIndex:0]);
1
NSLog(@"point?is?%@.",?NSStringFromCGPoint(point));
謝謝@bigParis的建議,可以用NSValue進(jìn)行基礎(chǔ)數(shù)據(jù)的保存,用這個(gè)方法更加清晰明確。
CGPoint??itemSprite1position?=?CGPointMake(100,?200);
NSValue?*originValue?=?[NSValue?valueWithCGPoint:itemSprite1position];
NSMutableArray?*?array??=?[[NSMutableArray?alloc]?initWithObjects:originValue,?nil];
//????從數(shù)組中取值的過(guò)程是這樣的:
NSValue?*currentValue?=?[array?objectAtIndex:0];
CGPoint?point?=?[currentValue?CGPointValue];
NSLog(@"point?is?%@.",?NSStringFromCGPoint(point));
現(xiàn)在Xcode7后OC支持泛型了,可以用NSMutableArray*array來(lái)保存。
四、 UIColor 獲取 RGB 值
UIColor?*color?=?[UIColor?colorWithRed:0.0?green:0.0?blue:1.0?alpha:1.0];
const?CGFloat?*components?=?CGColorGetComponents(color.CGColor);
NSLog(@"Red:?%f",?components[0]);
NSLog(@"Green:?%f",?components[1]);
NSLog(@"Blue:?%f",?components[2]);
NSLog(@"Alpha:?%f",?components[3]);
五、 修改textField的placeholder的字體顏色、大小
self.textField.placeholder?=?@"username?is?in?here!";
[self.textField?setValue:[UIColor?redColor]?forKeyPath:@"_placeholderLabel.textColor"];
[self.textField?setValue:[UIFont?boldSystemFontOfSize:16]?forKeyPath:@"_placeholderLabel.font"];
推薦
使用attributedString進(jìn)行設(shè)置.(感謝@HonglingHe的推薦)
NSString?*string?=?@"美麗新世界";
NSMutableAttributedString?*attributedString?=?[[NSMutableAttributedString?alloc]?initWithString:string];
[attributedString?addAttribute:NSForegroundColorAttributeName
value:[UIColor?redColor]
range:NSMakeRange(0,?[string?length])];
[attributedString?addAttribute:NSFontAttributeName
value:[UIFont?systemFontOfSize:16]
range:NSMakeRange(0,?[string?length])];
self.textField.attributedPlaceholder?=?attributedString;
六、兩點(diǎn)之間的距離
static?__inline__?CGFloat?CGPointDistanceBetweenTwoPoints(CGPoint?point1,?CGPoint?point2)?{?CGFloat?dx?=?point2.x?-?point1.x;?CGFloat?dy?=?point2.y?-?point1.y;?return?sqrt(dx*dx?+?dy*dy);}
七、IOS開(kāi)發(fā)-關(guān)閉/收起鍵盤(pán)方法總結(jié)
1、點(diǎn)擊Return按扭時(shí)收起鍵盤(pán)
-?(BOOL)textFieldShouldReturn:(UITextField?*)textField
{
return?[textField?resignFirstResponder];
}
2、點(diǎn)擊背景View收起鍵盤(pán)
[self.view?endEditing:YES];
3、你可以在任何地方加上這句話(huà),可以用來(lái)統(tǒng)一收起鍵盤(pán)
[[[UIApplication?sharedApplication]?keyWindow]?endEditing:YES];
八、在使用 ImagesQA.xcassets 時(shí)需要注意
將圖片直接拖入image到ImagesQA.xcassets中時(shí),圖片的名字會(huì)保留。
這個(gè)時(shí)候如果圖片的名字過(guò)長(zhǎng),那么這個(gè)名字會(huì)存入到ImagesQA.xcassets中,名字過(guò)長(zhǎng)會(huì)引起SourceTree判斷異常。
九、UIPickerView 判斷開(kāi)始選擇到選擇結(jié)束
開(kāi)始選擇的,需要在繼承UiPickerView,創(chuàng)建一個(gè)子類(lèi),在子類(lèi)中重載
-?(UIView*)hitTest:(CGPoint)point?withEvent:(UIEvent*)event
當(dāng)[super hitTest:point withEvent:event]返回不是nil的時(shí)候,說(shuō)明是點(diǎn)擊中UIPickerView中了。
結(jié)束選擇的, 實(shí)現(xiàn)UIPickerView的delegate方法
-?(void)pickerView:(UIPickerView*)pickerView?didSelectRow:(NSInteger)row?inComponent:(NSInteger)component
當(dāng)調(diào)用這個(gè)方法的時(shí)候,說(shuō)明選擇已經(jīng)結(jié)束了。
十、iOS模擬器 鍵盤(pán)事件
當(dāng)iOS模擬器 選擇了Keybaord->Connect Hardware keyboard 后,不彈出鍵盤(pán)。
當(dāng)代碼中添加了
[[NSNotificationCenter?defaultCenter]?addObserver:self
selector:@selector(keyboardWillHide)
name:UIKeyboardWillHideNotification
object:nil];
進(jìn)行鍵盤(pán)事件的獲取。那么在此情景下將不會(huì)調(diào)用- (void)keyboardWillHide.
因?yàn)闆](méi)有鍵盤(pán)的隱藏和顯示。
十一、在ios7上使用size classes后上面下面黑色
使用了size classes后,在ios7的模擬器上出現(xiàn)了上面和下面部分的黑色
可以在General->App Icons and Launch Images->Launch Images Source中設(shè)置Images.xcassets來(lái)解決。

十二、設(shè)置不同size在size classes
Font中設(shè)置不同的size classes。

十三、線程中更新 UILabel的text
[self.label1?performSelectorOnMainThread:@selector(setText:)??????????????????????????????????????withObject:textDisplay
waitUntilDone:YES];
label1 為UILabel,當(dāng)在子線程中,需要進(jìn)行text的更新的時(shí)候,可以使用這個(gè)方法來(lái)更新。
其他的UIView 也都是一樣的。
十四、使用UIScrollViewKeyboardDismissMode實(shí)現(xiàn)了Message app的行為
像Messages app一樣在滾動(dòng)的時(shí)候可以讓鍵盤(pán)消失是一種非常好的體驗(yàn)。然而,將這種行為整合到你的app很難。幸運(yùn)的是,蘋(píng)果給UIScrollView添加了一個(gè)很好用的屬性keyboardDismissMode,這樣可以方便很多。
現(xiàn)在僅僅只需要在Storyboard中改變一個(gè)簡(jiǎn)單的屬性,或者增加一行代碼,你的app可以和辦到和Messages app一樣的事情了。
這個(gè)屬性使用了新的UIScrollViewKeyboardDismissMode enum枚舉類(lèi)型。這個(gè)enum枚舉類(lèi)型可能的值如下:
typedef?NS_ENUM(NSInteger,?UIScrollViewKeyboardDismissMode)?{
UIScrollViewKeyboardDismissModeNone,
UIScrollViewKeyboardDismissModeOnDrag,??????//?dismisses?the?keyboard?when?a?drag?begins
UIScrollViewKeyboardDismissModeInteractive,?//?the?keyboard?follows?the?dragging?touch?off?screen,?and?may?be?pulled?upward?again?to?cancel?the?dismiss
}?NS_ENUM_AVAILABLE_IOS(7_0);
以下是讓鍵盤(pán)可以在滾動(dòng)的時(shí)候消失需要設(shè)置的屬性:

十五、報(bào)錯(cuò) "_sqlite3_bind_blob", referenced from:
將 sqlite3.dylib加載到framework
十六、ios7 statusbar 文字顏色
iOS7上,默認(rèn)status bar字體顏色是黑色的,要修改為白色的需要在infoPlist里設(shè)置UIViewControllerBasedStatusBarAppearance為NO,然后在代碼里添加:
[application?setStatusBarStyle:UIStatusBarStyleLightContent];
十七、獲得當(dāng)前硬盤(pán)空間
NSFileManager?*fm?=?[NSFileManager?defaultManager];
NSDictionary?*fattributes?=?[fm?attributesOfFileSystemForPath:NSHomeDirectory()?error:nil];
NSLog(@"容量%lldG",[[fattributes?objectForKey:NSFileSystemSize]?longLongValue]/1000000000);
NSLog(@"可用%lldG",[[fattributes?objectForKey:NSFileSystemFreeSize]?longLongValue]/1000000000);
十八、給UIView 設(shè)置透明度,不影響其他sub views
UIView設(shè)置了alpha值,但其中的內(nèi)容也跟著變透明。有沒(méi)有解決辦法?
設(shè)置background color的顏色中的透明度
比如:
[self.testView?setBackgroundColor:[UIColor?colorWithRed:0.0?green:1.0?blue:1.0?alpha:0.5]];
設(shè)置了color的alpha, 就可以實(shí)現(xiàn)背景色有透明度,當(dāng)其他sub views不受影響給color 添加 alpha,或修改alpha的值。
//?Returns?a?color?in?the?same?color?space?as?the?receiver?with?the?specified?alpha?component.
-?(UIColor?*)colorWithAlphaComponent:(CGFloat)alpha;
//?eg.
[view.backgroundColor?colorWithAlphaComponent:0.5];
十九、將color轉(zhuǎn)為UIImage
//將color轉(zhuǎn)為UIImage
-?(UIImage?*)createImageWithColor:(UIColor?*)color
{
CGRect?rect?=?CGRectMake(0.0f,?0.0f,?1.0f,?1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef?context?=?UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context,?[color?CGColor]);
CGContextFillRect(context,?rect);
UIImage?*theImage?=?UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return?theImage;
}
二十、NSTimer 用法
NSTimer?*timer?=?[NSTimer?scheduledTimerWithTimeInterval:.02?target:self?selector:@selector(tick:)?userInfo:nil?repeats:YES];
[[NSRunLoop?currentRunLoop]?addTimer:timer?forMode:NSRunLoopCommonModes];
在NSRunLoop?中添加定時(shí)器.
二十一、Bundle identifier 應(yīng)用標(biāo)示符
Bundle identifier 是應(yīng)用的標(biāo)示符,表明應(yīng)用和其他APP的區(qū)別。
二十二、NSDate 獲取幾年前的時(shí)間
eg. 獲取到40年前的日期
NSCalendar?*gregorian?=?[[NSCalendar?alloc]?initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents?*dateComponents?=?[[NSDateComponents?alloc]?init];
[dateComponents?setYear:-40];
self.birthDate?=?[gregorian?dateByAddingComponents:dateComponents?toDate:[NSDate?date]?options:0];
二十三、iOS加載啟動(dòng)圖的時(shí)候隱藏statusbar
只需需要在info.plist中加入Status bar is initially hidden 設(shè)置為YES就好

二十四、iOS 開(kāi)發(fā),工程中混合使用 ARC 和非ARC
Xcode 項(xiàng)目中我們可以使用 ARC 和非 ARC 的混合模式。
如果你的項(xiàng)目使用的非 ARC 模式,則為 ARC 模式的代碼文件加入 -fobjc-arc 標(biāo)簽。
如果你的項(xiàng)目使用的是 ARC 模式,則為非 ARC 模式的代碼文件加入 -fno-objc-arc 標(biāo)簽。
添加標(biāo)簽的方法:
打開(kāi):你的target -> Build Phases -> Compile Sources.
雙擊對(duì)應(yīng)的 *.m 文件
在彈出窗口中輸入上面提到的標(biāo)簽 -fobjc-arc / -fno-objc-arc
點(diǎn)擊 done 保存
二十五、iOS7 中 boundingRectWithSize:options:attributes:context:計(jì)算文本尺寸的使用
之前使用了NSString類(lèi)的sizeWithFont:constrainedToSize:lineBreakMode:方法,但是該方法已經(jīng)被iOS7 Deprecated了,而iOS7新出了一個(gè)boudingRectWithSize:options:attributes:context方法來(lái)代替。
而具體怎么使用呢,尤其那個(gè)attribute
NSDictionary?*attribute?=?@{NSFontAttributeName:?[UIFont?systemFontOfSize:13]};
CGSize?size?=?[@"相關(guān)NSString"?boundingRectWithSize:CGSizeMake(100,?0)?options:?NSStringDrawingTruncatesLastVisibleLine?|?NSStringDrawingUsesLineFragmentOrigin?|?NSStringDrawingUsesFontLeading?attributes:attribute?context:nil].size;
二十六、NSDate使用 注意
NSDate 在保存數(shù)據(jù),傳輸數(shù)據(jù)中,一般最好使用UTC時(shí)間。
在顯示到界面給用戶(hù)看的時(shí)候,需要轉(zhuǎn)換為本地時(shí)間。
二十七、在UIViewController中property的一個(gè)UIViewController的Present問(wèn)題
如果在一個(gè)UIViewController A中有一個(gè)property屬性為UIViewController B,實(shí)例化后,將BVC.view 添加到主UIViewController A.view上,如果在viewB上進(jìn)行- (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^)(void))completion NS_AVAILABLE_IOS(5_0);的操作將會(huì)出現(xiàn),“Presenting view controllers on detached view controllers is discouraged” 的問(wèn)題。
以為BVC已經(jīng)present到AVC中了,所以再一次進(jìn)行會(huì)出現(xiàn)錯(cuò)誤。
可以使用
[self.view.window.rootViewController?presentViewController:imagePicker
animated:YES
completion:^{
NSLog(@"Finished");
}];
來(lái)解決。
二十八、UITableViewCell indentationLevel 使用
UITableViewCell 屬性 NSInteger indentationLevel 的使用, 對(duì)cell設(shè)置 indentationLevel的值,可以將cell 分級(jí)別。
還有 CGFloat indentationWidth; 屬性,設(shè)置縮進(jìn)的寬度。
總縮進(jìn)的寬度:indentationLevel * indentationWidth
二十九、ActivityViewController 使用AirDrop分享
使用AirDrop 進(jìn)行分享:
NSArray?*array?=?@[@"test1",?@"test2"];
UIActivityViewController?*activityVC?=?[[UIActivityViewController?alloc]?initWithActivityItems:array?applicationActivities:nil];
[self?presentViewController:activityVC?animated:YES
completion:^{
NSLog(@"Air");
}];
就可以彈出界面:

三十、獲取CGRect的height
獲取CGRect的height, 除了self.createNewMessageTableView.frame.size.height這樣進(jìn)行點(diǎn)語(yǔ)法獲取。
還可以使用CGRectGetHeight(self.createNewMessageTableView.frame)進(jìn)行直接獲取。
除了這個(gè)方法還有func CGRectGetWidth(rect: CGRect) -> CGFloat
等等簡(jiǎn)單地方法
func CGRectGetMinX(rect: CGRect) -> CGFloat
func CGRectGetMidX(rect: CGRect) -> CGFloat
func CGRectGetMaxX(rect: CGRect) -> CGFloat
func CGRectGetMinY(rect: CGRect) -> CGFloat
三十一、打印 %
NSString?*printPercentStr?=?[NSString?stringWithFormat:@"%%"];
三十二、在工程中查看是否使用 IDFA
allentekiMac-mini:JiKaTongGit lihuaxie$ grep -r advertisingIdentifier .
grep: ./ios/Framework/AMapSearchKit.framework/Resources: No such file or directory
Binary file ./ios/Framework/MAMapKit.framework/MAMapKit matches
Binary file ./ios/Framework/MAMapKit.framework/Versions/2.4.1.e00ba6a/MAMapKit matches
Binary file ./ios/Framework/MAMapKit.framework/Versions/Current/MAMapKit matches
Binary file ./ios/JiKaTong.xcodeproj/project.xcworkspace/xcuserdata/lihuaxie.xcuserdatad/UserInterfaceState.xcuserstate matches
allentekiMac-mini:JiKaTongGit lihuaxie$
打開(kāi)終端,到工程目錄中, 輸入:
grep -r advertisingIdentifier .
可以看到那些文件中用到了IDFA,如果用到了就會(huì)被顯示出來(lái)。
三十三、APP 屏蔽 觸發(fā)事件
//?Disable?user?interaction?when?download?finishes
[[UIApplication?sharedApplication]?beginIgnoringInteractionEvents];
三十四、設(shè)置Status bar顏色
status bar的顏色設(shè)置:
1、如果沒(méi)有navigation bar, 直接設(shè)置
//?make?status?bar?background?color
self.view.backgroundColor?=?COLOR_APP_MAIN;
2、如果有navigation bar, 在navigation bar 添加一個(gè)view來(lái)設(shè)置顏色。
//?status?bar?color
UIView?*view?=?[[UIView?alloc]?initWithFrame:CGRectMake(0,?-20,?ScreenWidth,?20)];
[view?setBackgroundColor:COLOR_APP_MAIN];
[viewController.navigationController.navigationBar?addSubview:view];
三十五、NSDictionary 轉(zhuǎn) NSString
//?Start
NSDictionary?*parametersDic?=?[NSDictionary?dictionaryWithObjectsAndKeys:
self.providerStr,?KEY_LOGIN_PROVIDER,
token,?KEY_TOKEN,
response,?KEY_RESPONSE,
nil];
NSData?*jsonData?=?parametersDic?==?nil???nil?:?[NSJSONSerialization?dataWithJSONObject:parametersDic?options:0?error:nil];
NSString?*requestBody?=?[[NSString?alloc]?initWithData:jsonData?encoding:NSUTF8StringEncoding];
將dictionary?轉(zhuǎn)化為?NSData,?data?轉(zhuǎn)化為?string?.
三十六、iOS7 中UIButton setImage 沒(méi)有起作用
如果在iOS7 中進(jìn)行設(shè)置image 沒(méi)有生效。
那么說(shuō)明UIButton的 enable 屬性沒(méi)有生效是NO的。 需要設(shè)置enable 為YES。
三十七、User-Agent 判斷設(shè)備
UIWebView 會(huì)根據(jù)User-Agent 的值來(lái)判斷需要顯示哪個(gè)界面。
如果需要設(shè)置為全局,那么直接在應(yīng)用啟動(dòng)的時(shí)候加載。
-?(void)appendUserAgent
{
NSString?*oldAgent?=?[self.WebView?stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString?*newAgent?=?[oldAgent?stringByAppendingString:@"iOS"];
NSDictionary?*dic?=?[[NSDictionary?alloc]?initWithObjectsAndKeys:
newAgent,?@"UserAgent",?nil];
[[NSUserDefaults?standardUserDefaults]?registerDefaults:dic];
}
@“iOS" 為添加的自定義。
三十八、UIPasteboard 屏蔽paste 選項(xiàng)
當(dāng)UIpasteboard的string 設(shè)置為@“” 時(shí),那么string會(huì)成為nil。 就不會(huì)出現(xiàn)paste的選項(xiàng)。
三十九、class_addMethod 使用
當(dāng)ARC環(huán)境下
class_addMethod([self class], @selector(resolveThisMethodDynamically), (IMP) myMethodIMP, "v@:");
使用的時(shí)候@selector 需要使用super的class,不然會(huì)報(bào)錯(cuò)。
當(dāng)MRC環(huán)境下
class_addMethod([EmptyClass class], @selector(sayHello2), (IMP)sayHello, "v@:");
可以任意定義。但是系統(tǒng)會(huì)出現(xiàn)警告,忽略警告就可以。
四十、AFNetworking 傳送 form-data
將JSON的數(shù)據(jù),轉(zhuǎn)化為NSData,放入Request的body中。 發(fā)送到服務(wù)器就是form-data格式。
四十一、非空判斷注意
BOOL?hasBccCode?=?YES;
if?(?nil?==?bccCodeStr
||?[bccCodeStr?isKindOfClass:[NSNull?class]]
||?[bccCodeStr?isEqualToString:@""])
{
hasBccCode?=?NO;
}
如果進(jìn)行非空判斷和類(lèi)型判斷時(shí),需要新進(jìn)行類(lèi)型判斷,再進(jìn)行非空判斷,不然會(huì)crash。
四十二、iOS 8.4 UIAlertView 鍵盤(pán)顯示問(wèn)題
可以在調(diào)用UIAlertView 之前進(jìn)行鍵盤(pán)是否已經(jīng)隱藏的判斷。
@property?(nonatomic,?assign)?BOOL?hasShowdKeyboard;
[[NSNotificationCenter?defaultCenter]?addObserver:self
selector:@selector(showKeyboard)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter?defaultCenter]?addObserver:self
selector:@selector(dismissKeyboard)
name:UIKeyboardDidHideNotification
object:nil];
-?(void)showKeyboard
{
self.hasShowdKeyboard?=?YES;
}
-?(void)dismissKeyboard
{
self.hasShowdKeyboard?=?NO;
}
while?(?self.hasShowdKeyboard?)
{
[[NSRunLoop?currentRunLoop]?runMode:NSDefaultRunLoopMode?beforeDate:[NSDate?distantFuture]];
}
UIAlertView*?alerview?=?[[UIAlertView?alloc]?initWithTitle:@""?message:@"取消修改?"?delegate:self?cancelButtonTitle:@"取消"?otherButtonTitles:?@"確定",?nil];
[alerview?show];
四十三、模擬器中文輸入法設(shè)置
模擬器默認(rèn)的配置種沒(méi)有“小地球”,只能輸入英文。加入中文方法如下:
選擇Settings--->General-->Keyboard-->International KeyBoards-->Add New Keyboard-->Chinese Simplified(PinYin) 即我們一般用的簡(jiǎn)體中文拼音輸入法,配置好后,再輸入文字時(shí),點(diǎn)擊彈出鍵盤(pán)上的“小地球”就可以輸入中文了。
如果不行,可以長(zhǎng)按“小地球”選擇中文。
四十四、iPhone number pad
1、phone 的鍵盤(pán)類(lèi)型:
number pad 只能輸入數(shù)字,不能切換到其他輸入

2、phone pad 類(lèi)型: 撥打電話(huà)的時(shí)候使用,可以輸入數(shù)字和 + * #

四十五、UIView 自帶動(dòng)畫(huà)翻轉(zhuǎn)界面
-?(IBAction)changeImages:(id)sender
{
CGContextRef?context?=?UIGraphicsGetCurrentContext();
[UIView?beginAnimations:nil?context:context];
[UIView?setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView?setAnimationDuration:1.0];
[UIView?setAnimationTransition:UIViewAnimationTransitionCurlDown?forView:_parentView?cache:YES];
[UIView?setAnimationTransition:UIViewAnimationTransitionCurlUp?forView:_parentView?cache:YES];
[UIView?setAnimationTransition:UIViewAnimationTransitionFlipFromLeft?forView:_parentView?cache:YES];
[UIView?setAnimationTransition:UIViewAnimationTransitionFlipFromRight?forView:_parentView?cache:YES];
NSInteger?purple?=?[[_parentView?subviews]?indexOfObject:self.image1];
NSInteger?maroon?=?[[_parentView?subviews]?indexOfObject:self.image2];
[_parentView?exchangeSubviewAtIndex:purple?withSubviewAtIndex:maroon];
[UIView?setAnimationDelegate:self];
[UIView?commitAnimations];
}
四十六、KVO 監(jiān)聽(tīng)其他類(lèi)的變量
[[HXSLocationManager?sharedManager]?addObserver:self
forKeyPath:@"currentBoxEntry.boxCodeStr"
options:NSKeyValueObservingOptionNew?|?NSKeyValueObservingOptionInitial?|?NSKeyValueObservingOptionOld?context:nil];
在實(shí)現(xiàn)的類(lèi)self中,進(jìn)行[HXSLocationManager sharedManager]類(lèi)中的變量@“currentBoxEntry.boxCodeStr” 監(jiān)聽(tīng)。
四十七、ios9 crash animateWithDuration
在iOS9 中,如果進(jìn)行animateWithDuration 時(shí),view被release 那么會(huì)引起crash。
[UIView?animateWithDuration:0.25f?animations:^{
self.frame?=?selfFrame;
}?completion:^(BOOL?finished)?{
if?(finished)?{
[super?removeFromSuperview];
}
}];
會(huì)crash。
[UIView?animateWithDuration:0.25f
delay:0
usingSpringWithDamping:1.0
initialSpringVelocity:1.0?options:UIViewAnimationOptionCurveLinear
animations:^{
self.frame?=?selfFrame;
}?completion:^(BOOL?finished)?{
[super?removeFromSuperview];
}];
不會(huì)Crash。
四十八、對(duì)NSString進(jìn)行URL編碼轉(zhuǎn)換
iPTV項(xiàng)目中在刪除影片時(shí),URL中需傳送用戶(hù)名與影片ID兩個(gè)參數(shù)。當(dāng)用戶(hù)名中帶中文字符時(shí),刪除失敗。
之前測(cè)試時(shí),手機(jī)號(hào)綁定的用戶(hù)名是英文或數(shù)字。換了手機(jī)號(hào)測(cè)試時(shí)才發(fā)現(xiàn)這個(gè)問(wèn)題。
對(duì)于URL中有中文字符的情況,需對(duì)URL進(jìn)行編碼轉(zhuǎn)換。
urlStr?=?[urlStr?stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
四十九、Xcode iOS加載圖片只能用PNG
雖然在Xcode可以看到j(luò)pg的圖片,但是在加載的時(shí)候會(huì)失敗。
錯(cuò)誤為 Could not load the "ReversalImage1" image referenced from a nib in the bun
必須使用PNG的圖片。
如果需要使用JPG 需要添加后綴
[UIImage?imageNamed:@"myImage.jpg"];
五十、保存全屏為image
CGSize?imageSize?=?[[UIScreen?mainScreen]?bounds].size;
UIGraphicsBeginImageContextWithOptions(imageSize,?NO,?0);
CGContextRef?context?=?UIGraphicsGetCurrentContext();
for?(UIWindow?*?window?in?[[UIApplication?sharedApplication]?windows])?{
if?(![window?respondsToSelector:@selector(screen)]?||?[window?screen]?==?[UIScreen?mainScreen])?{
CGContextSaveGState(context);
CGContextTranslateCTM(context,?[window?center].x,?[window?center].y);
CGContextConcatCTM(context,?[window?transform]);
CGContextTranslateCTM(context,?-[window?bounds].size.width*[[window?layer]?anchorPoint].x,?-[window?bounds].size.height*[[window?layer]?anchorPoint].y);
[[window?layer]?renderInContext:context];
CGContextRestoreGState(context);
}
}
UIImage?*image?=?UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
五十一、判斷定位狀態(tài) locationServicesEnabled
這個(gè)[CLLocationManager locationServicesEnabled]檢測(cè)的是整個(gè)iOS系統(tǒng)的位置服務(wù)開(kāi)關(guān),無(wú)法檢測(cè)當(dāng)前應(yīng)用是否被關(guān)閉。通過(guò)
CLAuthorizationStatus?status?=?[CLLocationManager?authorizationStatus];
if?(kCLAuthorizationStatusDenied?==?status?||?kCLAuthorizationStatusRestricted?==?status)?{
[self?locationManager:self.locationManager?didUpdateLocations:nil];
}?else?{?//?the?user?has?closed?this?function
[self.locationManager?startUpdatingLocation];
}
CLAuthorizationStatus來(lái)判斷是否可以訪問(wèn)GPS
五十二、微信分享的時(shí)候注意大小
text 的大小必須 大于0 小于 10k
image 必須 小于 64k
url 必須 大于 0k
五十三、圖片緩存的清空
一般使用SDWebImage 進(jìn)行圖片的顯示和緩存,一般緩存的內(nèi)容比較多了就需要進(jìn)行清空緩存
清除SDWebImage的內(nèi)存和硬盤(pán)時(shí),可以同時(shí)清除session 和 cookie的緩存。
//?清理內(nèi)存
[[SDImageCache?sharedImageCache]?clearMemory];
//?清理webview?緩存
NSHTTPCookieStorage?*storage?=?[NSHTTPCookieStorage?sharedHTTPCookieStorage];
for?(NSHTTPCookie?*cookie?in?[storage?cookies])?{
[storage?deleteCookie:cookie];
}
NSURLSessionConfiguration?*config?=?[NSURLSessionConfiguration?defaultSessionConfiguration];
[config.URLCache?removeAllCachedResponses];
[[NSURLCache?sharedURLCache]?removeAllCachedResponses];
//?清理硬盤(pán)
[[SDImageCache?sharedImageCache]?clearDiskOnCompletion:^{
[MBProgressHUD?hideAllHUDsForView:self.view?animated:YES];
[self.tableView?reloadData];
}];
五十四、TableView Header View 跟隨Tableview 滾動(dòng)
當(dāng)tableview的類(lèi)型為 plain的時(shí)候,header View 就會(huì)停留在最上面。
當(dāng)類(lèi)型為 group的時(shí)候,header view 就會(huì)跟隨tableview 一起滾動(dòng)了。
五十五、TabBar的title 設(shè)置
在xib 或 storyboard 中可以進(jìn)行tabBar的設(shè)置

其中badge 是自帶的在圖標(biāo)上添加一個(gè)角標(biāo)。
1. self.navigationItem.title 設(shè)置navigation的title 需要用這個(gè)進(jìn)行設(shè)置。
2. self.title 在tab bar的主VC 中,進(jìn)行設(shè)置self.title 會(huì)導(dǎo)致navigation 的title 和 tab bar的title一起被修改。
五十六、UITabBar,移除頂部的陰影
添加這兩行代碼:
[[UITabBar?appearance]?setShadowImage:[[UIImage?alloc]?init]];
[[UITabBar?appearance]?setBackgroundImage:[[UIImage?alloc]?init]];
頂部的陰影是在UIWindow上的,所以不能簡(jiǎn)單的設(shè)置就去除。
五十七、當(dāng)一行中,多個(gè)UIKit 都是動(dòng)態(tài)的寬度設(shè)置

設(shè)置horizontal的值,表示出現(xiàn)內(nèi)容很長(zhǎng)的時(shí)候,優(yōu)先壓縮這個(gè)UIKit。
五十八、JSON的“” 轉(zhuǎn)換為nil
使用AFNetworking 時(shí), 使用
AFJSONResponseSerializer?*response?=?[[AFJSONResponseSerializer?alloc]?init];
response.removesKeysWithNullValues?=?YES;
_sharedClient.responseSerializer?=?response;
這個(gè)參數(shù) removesKeysWithNullValues 可以將null的值刪除,那么就Value為nil了
// END
寫(xiě)吐了,那么長(zhǎng)應(yīng)該是沒(méi)人會(huì)看完的,看完了算你狠。在iOS開(kāi)發(fā)中經(jīng)常需要使用的或不常用的知識(shí)點(diǎn)的總結(jié),幾年的收藏和積累(踩過(guò)的坑)。