在iOS開發中常常須要使用的或不經常使用的知識點的總結,幾年的收藏和積累(踩過的坑)。ios
手機型號 | 屏幕尺寸 |
---|---|
iPhone 4 4s | 320 * 480 |
iPhone 5 5s | 320 * 568 |
iPhone 6 6s | 375 * 667 |
iphone 6 plus 6s plus | 414 * 736 |
1
2
3
|
UIColor *whiteColor = [UIColor whiteColor];
NSDictionary *dic = [NSDictionary dictionaryWithObject:whiteColor forKey:NSForegroundColorAttributeName];
[self.navigationController.navigationBar setTitleTextAttributes:dic];
|
1
2
3
4
5
6
|
CGPoint itemSprite1position = CGPointMake(100, 200);
NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:NSStringFromCGPoint(itemSprite1position),nil];
// 從數組中取值的過程是這樣的:
CGPoint point = CGPointFromString([array objectAtIndex:0]);
NSLog(@"point is %@.", NSStringFromCGPoint(point));
|
謝謝@bigParis的建議,能夠用NSValue進行基礎數據的保存,用這個方法更加清晰明確。git
1
2
3
4
5
6
7
8
|
CGPoint itemSprite1position = CGPointMake(100, 200);
NSValue *originValue = [NSValue valueWithCGPoint:itemSprite1position];
NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:originValue, nil];
// 從數組中取值的過程是這樣的:
NSValue *currentValue = [array objectAtIndex:0];
CGPoint point = [currentValue CGPointValue];
NSLog(@"point is %@.", NSStringFromCGPoint(point));
|
如今Xcode7後OC支持泛型了,能夠用NSMutableArray *array
來保存。github
1
2
3
4
5
6
|
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]);
|
1
2
3
|
self.textField.placeholder = @"username is in here!";
[self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[self.textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
|
1
|
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);}
|
一、點擊Return按扭時收起鍵盤web
1
2
3
4
|
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
return [textField resignFirstResponder];
}
|
二、點擊背景View收起鍵盤(你的View必須是繼承於UIControl)sql
1
|
[self.view endEditing:YES];
|
三、你能夠在任何地方加上這句話,能夠用來統一收起鍵盤json
1
|
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
|
將圖片直接拖入image到ImagesQA.xcassets中時,圖片的名字會保留。
這個時候若是圖片的名字過長,那麼這個名字會存入到ImagesQA.xcassets中,名字過長會引發SourceTree判斷異常。windows
開始選擇的,須要在繼承UiPickerView,建立一個子類,在子類中重載數組
1
|
- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event
|
當[super hitTest:point withEvent:event]
返回不是nil的時候,說明是點擊中UIPickerView中了。
結束選擇的, 實現UIPickerView的delegate方法xcode
1
|
- (void)pickerView:(UIPickerView*)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
|
當調用這個方法的時候,說明選擇已經結束了。緩存
當iOS模擬器 選擇了Keybaord->Connect Hardware keyboard 後,不彈出鍵盤。
當代碼中添加了
1
2
3
4
|
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide)
name:UIKeyboardWillHideNotification
object:nil];
|
進行鍵盤事件的獲取。那麼在此情景下將不會調用- (void)keyboardWillHide
.
由於沒有鍵盤的隱藏和顯示。
使用了size classes後,在ios7的模擬器上出現了上面和下面部分的黑色
能夠在General->App Icons and Launch Images->Launch Images Source中設置Images.xcassets來解決。
Font中設置不一樣的size classes。
1
2
|
[self.label1 performSelectorOnMainThread:@selector(setText:) withObject:textDisplay
waitUntilDone:YES];
|
label1 爲UILabel,當在子線程中,須要進行text的更新的時候,可使用這個方法來更新。
其餘的UIView 也都是同樣的。
像Messages app同樣在滾動的時候可讓鍵盤消失是一種很是好的體驗。然而,將這種行爲整合到你的app很難。幸運的是,蘋果給UIScrollView添加了一個很好用的屬性keyboardDismissMode,這樣能夠方便不少。
如今僅僅只須要在Storyboard中改變一個簡單的屬性,或者增長一行代碼,你的app能夠和辦到和Messages app同樣的事情了。
這個屬性使用了新的UIScrollViewKeyboardDismissMode enum枚舉類型。這個enum枚舉類型可能的值以下:
1
2
3
4
5
|
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);
|
如下是讓鍵盤能夠在滾動的時候消失須要設置的屬性:
將 sqlite3.dylib加載到framework
iOS7上,默認status bar字體顏色是黑色的,要修改成白色的須要在infoPlist裏設置UIViewControllerBasedStatusBarAppearance爲NO,而後在代碼裏添加:[application setStatusBarStyle:UIStatusBarStyleLightContent];
1
2
3
4
5
|
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設置了alpha值,但其中的內容也跟着變透明。有沒有解決辦法?
設置background color的顏色中的透明度
好比:
1
|
[self.testView setBackgroundColor:[UIColor colorWithRed:0.0 green:1.0 blue:1.0 alpha:0.5]];
|
設置了color的alpha, 就能夠實現背景色有透明度,當其餘sub views不受影響給color 添加 alpha,或修改alpha的值。
1
2
3
4
|
// 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];
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
//將color轉爲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;
}
|
1
2
3
|
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(tick:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
|
在NSRunLoop 中添加定時器.
Bundle identifier 是應用的標示符,代表應用和其餘APP的區別。
eg. 獲取到40年前的日期
1
2
3
4
|
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear:-40];
self.birthDate = [gregorian dateByAddingComponents:dateComponents toDate:[NSDate date] options:0];
|
只需須要在info.plist中加入Status bar is initially hidden 設置爲YES就好
Xcode 項目中咱們可使用 ARC 和非 ARC 的混合模式。
若是你的項目使用的非 ARC 模式,則爲 ARC 模式的代碼文件加入 -fobjc-arc 標籤。
若是你的項目使用的是 ARC 模式,則爲非 ARC 模式的代碼文件加入 -fno-objc-arc 標籤。
添加標籤的方法:
以前使用了NSString類的sizeWithFont:constrainedToSize:lineBreakMode:方法,可是該方法已經被iOS7 Deprecated了,而iOS7新出了一個boudingRectWithSize:options:attributes:context方法來代替。
而具體怎麼使用呢,尤爲那個attribute
1
2
|
NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:13]};
CGSize size = [@"相關NSString" boundingRectWithSize:CGSizeMake(100, 0) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
|
NSDate 在保存數據,傳輸數據中,通常最好使用UTC時間。
在顯示到界面給用戶看的時候,須要轉換爲本地時間。
若是在一個UIViewController A中有一個property屬性爲UIViewController B,實例化後,將BVC.view 添加到主UIViewController A.view上,若是在viewB上進行 - (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^)(void))completion NS_AVAILABLE_IOS(5_0);
的操做將會出現,「 Presenting view controllers on detached view controllers is discouraged 」 的問題。
覺得BVC已經present到AVC中了,因此再一次進行會出現錯誤。
可使用
1
2
3
4
5
|
[self.view.window.rootViewController presentViewController:imagePicker
animated:YES
completion:^{
NSLog(@"Finished");
}];
|
來解決。
UITableViewCell 屬性 NSInteger indentationLevel 的使用, 對cell設置 indentationLevel的值,能夠將cell 分級別。
還有 CGFloat indentationWidth; 屬性,設置縮進的寬度。
總縮進的寬度: indentationLevel * indentationWidth
使用AirDrop 進行分享:
1
2
3
4
5
6
7
8
|
NSArray *array = @[@"test1", @"test2"];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:array applicationActivities:nil];
[self presentViewController:activityVC animated:YES
completion:^{
NSLog(@"Air");
}];
|
就能夠彈出界面:
獲取CGRect的height, 除了 self.createNewMessageTableView.frame.size.height
這樣進行點語法獲取。
還可使用CGRectGetHeight(self.createNewMessageTableView.frame)
進行直接獲取。
除了這個方法還有 func CGRectGetWidth(rect: CGRect) -> CGFloat
等等簡單地方法
1
2
3
4
|
func CGRectGetMinX(rect: CGRect) -> CGFloat
func CGRectGetMidX(rect: CGRect) -> CGFloat
func CGRectGetMaxX(rect: CGRect) -> CGFloat
func CGRectGetMinY(rect: CGRect) -> CGFloat
|
1
|
NSString *printPercentStr = [NSString stringWithFormat:@"%%"];
|
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$
打開終端,到工程目錄中, 輸入:
grep -r advertisingIdentifier .
能夠看到那些文件中用到了IDFA,若是用到了就會被顯示出來。
1
2
|
// Disable user interaction when download finishes
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
|
status bar的顏色設置:
1
|
self.view.backgroundColor = COLOR_APP_MAIN;
|
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, -20, ScreenWidth, 20)];
[view setBackgroundColor:COLOR_APP_MAIN];
[viewController.navigationController.navigationBar addSubview:view];
1
|
####三十5、NSDictionary 轉 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];
1
2
3
4
5
6
7
8
9
10
|
將
dictionary 轉化爲 NSData, data 轉化爲 string .
####三十6、iOS7 中UIButton setImage 沒有起做用
若是在
iOS7 中進行設置image 沒有生效。
那麼說明
UIButton的 enable 屬性沒有生效是NO的。 **須要設置enable 爲YES。**
####三十7、User-Agent 判斷設備
UIWebView 會根據User-Agent 的值來判斷須要顯示哪一個界面。
若是須要設置爲全局,那麼直接在應用啓動的時候加載。
|
(void)appendUserAgent
{
NSString oldAgent = [self.WebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString newAgent = [oldAgent stringByAppendingString:@"iOS"];
NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:
1
|
newAgent, @"UserAgent", nil];
|
[[NSUserDefaults standardUserDefaults] registerDefaults:dic];
}
@「iOS」 爲添加的自定義。
當UIpasteboard的string 設置爲@「」 時,那麼string會成爲nil。 就不會出現paste的選項。
當 ARC 環境下
class_addMethod([self class], @selector(resolveThisMethodDynamically), (IMP) myMethodIMP, 「v@:」);
使用的時候@selector 須要使用super的class,否則會報錯。
當MRC環境下
class_addMethod([EmptyClass class], @selector(sayHello2), (IMP)sayHello, 「v@:」);
能夠任意定義。可是系統會出現警告,忽略警告就能夠。
將JSON的數據,轉化爲NSData, 放入Request的body中。 發送到服務器就是form-data格式。
1
2
3
4
5
6
7
|
BOOL hasBccCode = YES;
if ( nil == bccCodeStr
|| [bccCodeStr isKindOfClass:[NSNull class]]
|| [bccCodeStr isEqualToString:@""])
{
hasBccCode = NO;
}
|
若是進行非空判斷和類型判斷時,須要新進行類型判斷,再進行非空判斷,否則會crash。
能夠在調用UIAlertView 以前進行鍵盤是否已經隱藏的判斷。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
@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];
|
模擬器默認的配置種沒有「小地球」,只能輸入英文。加入中文方法以下:
選擇Settings—>General–>Keyboard–>International KeyBoards–>Add New Keyboard–>Chinese Simplified(PinYin) 即咱們通常用的簡體中文拼音輸入法,配置好後,再輸入文字時,點擊彈出鍵盤上的「小地球」就能夠輸入中文了。
若是不行,能夠長按「小地球」選擇中文。
phone 的鍵盤類型:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
- (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];
}
|
1
2
3
|
[[HXSLocationManager sharedManager] addObserver:self
forKeyPath:@"currentBoxEntry.boxCodeStr"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionOld context:nil];
|
在實現的類self中,進行[HXSLocationManager sharedManager]類中的變量@「currentBoxEntry.boxCodeStr」 監聽。
在iOS9 中,若是進行animateWithDuration 時,view被release 那麼會引發crash。
1
2
3
4
5
6
7
|
[UIView animateWithDuration:0.25f animations:^{
self.frame = selfFrame;
} completion:^(BOOL finished) {
if (finished) {
[super removeFromSuperview];
}
}];
|
會crash。
1
2
3
4
5
6
7
8
9
|
[UIView animateWithDuration:0.25f
delay:0
usingSpringWithDamping:1.0
initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveLinear
animations:^{
self.frame = selfFrame;
} completion:^(BOOL finished) {
[super removeFromSuperview];
}];
|
不會Crash。
iPTV項目中在刪除影片時,URL中需傳送用戶名與影片ID兩個參數。當用戶名中帶中文字符時,刪除失敗。
以前測試時,手機號綁定的用戶名是英文或數字。換了手機號測試時才發現這個問題。
對於URL中有中文字符的狀況,需對URL進行編碼轉換。
1
|
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
|
雖然在Xcode能夠看到jpg的圖片,可是在加載的時候會失敗。
錯誤爲 Could not load the 「ReversalImage1」 image referenced from a nib in the bun
必須使用PNG的圖片。
若是須要使用JPG 須要添加後綴
1
|
[UIImage imageNamed:@"myImage.jpg"];
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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();
|
這個[CLLocationManager locationServicesEnabled]檢測的是整個iOS系統的位置服務開關,沒法檢測當前應用是否被關閉。經過
1
2
3
4
5
6
|
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來判斷是否能夠訪問GPS
text 的大小必須 大於0 小於 10k
image 必須 小於 64k
url 必須 大於 0k
通常使用SDWebImage 進行圖片的顯示和緩存,通常緩存的內容比較多了就須要進行清空緩存
清除SDWebImage的內存和硬盤時,能夠同時清除session 和 cookie的緩存。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
// 清理內存
[[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];
// 清理硬盤
[[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
[self.tableView reloadData];
}];
|
當tableview的類型爲 plain的時候,header View 就會停留在最上面。
當類型爲 group的時候,header view 就會跟隨tableview 一塊兒滾動了。
在xib 或 storyboard 中能夠進行tabBar的設置
其中badge 是自帶的在圖標上添加一個角標。
1. self.navigationItem.title 設置navigation的title 須要用這個進行設置。
2. self.title 在tab bar的主VC 中,進行設置self.title 會致使navigation 的title 和 tab bar的title一塊兒被修改。
添加這兩行代碼:
1
2
|
[[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
[[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];
|
頂部的陰影是在UIWindow上的,因此不能簡單的設置就去除。
設置horizontal的值,表示出現內容很長的時候,優先壓縮這個UIKit。
使用AFNetworking 時, 使用
1
2
3
4
|
AFJSONResponseSerializer *response = [[AFJSONResponseSerializer alloc] init];
response.removesKeysWithNullValues = YES;
_sharedClient.responseSerializer = response;
|
這個參數 removesKeysWithNullValues 能夠將null的值刪除,那麼就Value爲nil了
// END