天天看點

[紹棠] iOS開發經驗總結

一、 iPhone Size

手機型号 螢幕尺寸
iPhone 4 4s 320 * 480
iPhone 5 5s 320 * 568
iPhone 6 6s 375 * 667
iphone 6 plus 6s plus 414 * 736

二、 給navigation Bar 設定 title 顔色

UIColor *whiteColor = [UIColor whiteColor];
NSDictionary *dic = [NSDictionary dictionaryWithObject:whiteColor forKey:NSForegroundColorAttributeName]; [self.navigationController.navigationBar setTitleTextAttributes:dic];
           

三、 如何把一個CGPoint存入數組裡

謝謝@bigParis的建議,可以用NSValue進行基礎資料的儲存,用這個方法更加清晰明确。

現在Xcode7後OC支援泛型了,可以用

NSMutableArray<NSString *> *array

來儲存。

四、 UIColor 擷取 RGB 值

五、 修改textField的placeholder的字型顔色、大小

self.textField.placeholder = @"username is in here!";
[self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"]; [self.textField setValue:[UIFont boldSystemFontOfSize:
           

六、兩點之間的距離

七、IOS開發-關閉/收起鍵盤方法總結

1、點選Return按扭時收起鍵盤

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{
    return [textField resignFirstResponder]; 
}
           

2、點選背景View收起鍵盤(你的View必須是繼承于UIControl)

3、你可以在任何地方加上這句話,可以用來統一收起鍵盤

八、在使用 ImagesQA.xcassets 時需要注意

将圖檔直接拖入image到ImagesQA.xcassets中時,圖檔的名字會保留。

這個時候如果圖檔的名字過長,那麼這個名字會存入到ImagesQA.xcassets中,名字過長會引起SourceTree判斷異常。

九、UIPickerView 判斷開始選擇到選擇結束

開始選擇的,需要在繼承UiPickerView,建立一個子類,在子類中重載

[super hitTest:point withEvent:event]

傳回不是nil的時候,說明是點選中UIPickerView中了。

結束選擇的, 實作UIPickerView的delegate方法

當調用這個方法的時候,說明選擇已經結束了。

十、iOS模拟器 鍵盤事件

當iOS模拟器 選擇了Keybaord->Connect Hardware keyboard 後,不彈出鍵盤。

當代碼中添加了

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
           

進行鍵盤事件的擷取。那麼在此情景下将不會調用

- (void)keyboardWillHide

.

因為沒有鍵盤的隐藏和顯示。

十一、在ios7上使用size classes後上面下面黑色

使用了size classes後,在ios7的模拟器上出現了上面和下面部分的黑色

可以在General->App Icons and Launch Images->Launch Images Source中設定Images.xcassets來解決。

[紹棠] iOS開發經驗總結

十一.png

十二、設定不同size在size classes

Font中設定不同的size classes。

[紹棠] iOS開發經驗總結

十二.png

十三、線程中更新 UILabel的text

[self.label1 performSelectorOnMainThread:@selector(setText:)                                      withObject:textDisplay
                                   waitUntilDone:YES];
           

label1 為UILabel,當在子線程中,需要進行text的更新的時候,可以使用這個方法來更新。

其他的UIView 也都是一樣的。

十四、使用UIScrollViewKeyboardDismissMode實作了Message app的行為

像Messages app一樣在滾動的時候可以讓鍵盤消失是一種非常好的體驗。然而,将這種行為整合到你的app很難。幸運的是,蘋果給UIScrollView添加了一個很好用的屬性keyboardDismissMode,這樣可以友善很多。

現在僅僅隻需要在Storyboard中改變一個簡單的屬性,或者增加一行代碼,你的app可以和辦到和Messages app一樣的事情了。

這個屬性使用了新的UIScrollViewKeyboardDismissMode enum枚舉類型。這個enum枚舉類型可能的值如下:

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(
           

以下是讓鍵盤可以在滾動的時候消失需要設定的屬性:

[紹棠] iOS開發經驗總結

十四.png

十五、報錯 "_sqlite3_bind_blob", referenced from:

将 sqlite3.dylib加載到framework 

十六、ios7 statusbar 文字顔色

iOS7上,預設status bar字型顔色是黑色的,要修改為白色的需要在infoPlist裡設定UIViewControllerBasedStatusBarAppearance為NO,然後在代碼裡添加:

[application setStatusBarStyle:UIStatusBarStyleLightContent];

十七、獲得目前硬碟空間

NSFileManager *fm = [NSFileManager defaultManager];
    NSDictionary *fattributes = [fm attributesOfFileSystemForPath:NSHomeDirectory() error:nil]; NSLog(@"容量%lldG",[[fattributes objectForKey:NSFileSystemSize] longLongValue]/
           

十八、給UIView 設定透明度,不影響其他sub views

UIView設定了alpha值,但其中的内容也跟着變透明。有沒有解決辦法?

設定background color的顔色中的透明度

比如:

設定了color的alpha, 就可以實作背景色有透明度,當其他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:
           

十九、将color轉為UIImage

//将color轉為UIImage
- (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(
           

二十、NSTimer 用法

在NSRunLoop 中添加定時器.

二十一、Bundle identifier 應用标示符

Bundle identifier 是應用的标示符,表明應用和其他APP的差別。

二十二、NSDate 擷取幾年前的時間

eg. 擷取到40年前的日期

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init]; [dateComponents setYear:-
           

二十三、iOS加載啟動圖的時候隐藏statusbar

隻需需要在info.plist中加入Status bar is initially hidden 設定為YES就好

[紹棠] iOS開發經驗總結

二十三.jpg

二十四、iOS 開發,工程中混合使用 ARC 和非ARC

Xcode 項目中我們可以使用 ARC 和非 ARC 的混合模式。

如果你的項目使用的非 ARC 模式,則為 ARC 模式的代碼檔案加入 -fobjc-arc 标簽。

如果你的項目使用的是 ARC 模式,則為非 ARC 模式的代碼檔案加入 -fno-objc-arc 标簽。

添加标簽的方法:

  • 打開:你的target -> Build Phases -> Compile Sources.
  • 輕按兩下對應的 *.m 檔案
  • 在彈出視窗中輸入上面提到的标簽 -fobjc-arc / -fno-objc-arc
  • 點選 done 儲存

二十五、iOS7 中 boundingRectWithSize:options:attributes:context:計算文本尺寸的使用

之前使用了NSString類的sizeWithFont:constrainedToSize:lineBreakMode:方法,但是該方法已經被iOS7 Deprecated了,而iOS7新出了一個boudingRectWithSize:options:attributes:context方法來代替。

而具體怎麼使用呢,尤其那個attribute

二十六、NSDate使用 注意

NSDate 在儲存資料,傳輸資料中,一般最好使用UTC時間。

在顯示到界面給使用者看的時候,需要轉換為本地時間。

二十七、在UIViewController中property的一個UIViewController的Present問題

如果在一個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中了,是以再一次進行會出現錯誤。

可以使用

[self.view.window.rootViewController presentViewController:imagePicker
                                                      animated:YES completion:^{ NSLog(@"Finished"); }];
           

來解決。

二十八、UITableViewCell indentationLevel 使用

UITableViewCell 屬性 NSInteger indentationLevel 的使用, 對cell設定 indentationLevel的值,可以将cell 分級别。

還有 CGFloat indentationWidth; 屬性,設定縮進的寬度。

總縮進的寬度: indentationLevel * indentationWidth

二十九、ActivityViewController 使用AirDrop分享

使用AirDrop 進行分享:

NSArray *array = @[@"test1", @"test2"];

UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:array applicationActivities:nil]; [self presentViewController:activityVC animated:YES completion:^{ NSLog(@"Air"); }];
           

就可以彈出界面:

[紹棠] iOS開發經驗總結

二十九.png

三十、擷取CGRect的height

擷取CGRect的height, 除了 

self.createNewMessageTableView.frame.size.height

 這樣進行點文法擷取。

還可以使用

CGRectGetHeight(self.createNewMessageTableView.frame)

 進行直接擷取。

除了這個方法還有  

func CGRectGetWidth(rect: CGRect) -> CGFloat

等等簡單地方法

三十一、列印 %

三十二、在工程中檢視是否使用 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$

打開終端,到工程目錄中, 輸入:

grep -r advertisingIdentifier .

可以看到那些檔案中用到了IDFA,如果用到了就會被顯示出來。

三十三、APP 屏蔽 觸發事件

// Disable user interaction when download finishes
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
           

三十四、設定Status bar顔色

status bar的顔色設定:

  1. 如果沒有navigation bar, 直接設定 // make status bar background color
  2. 如果有navigation bar, 在navigation bar 添加一個view來設定顔色。// status bar color

    ```

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, -20, ScreenWidth, 20)];

    [view setBackgroundColor:COLOR_APP_MAIN];

[viewController.navigationController.navigationBar addSubview:view];

####三十五、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];

将dictionary 轉化為 NSData, data 轉化為 string .

####三十六、iOS7 中UIButton setImage 沒有起作用
如果在iOS7 中進行設定image 沒有生效。

那麼說明UIButton的 enable 屬性沒有生效是NO的。 **需要設定enable 為YES。** ####三十七、User-Agent 判斷裝置 UIWebView 會根據User-Agent 的值來判斷需要顯示哪個界面。 如果需要設定為全局,那麼直接在應用啟動的時候加載。
           
  • (void)appendUserAgent

    {

    NSString oldAgent = [self.WebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

    NSString newAgent = [oldAgent stringByAppendingString:@"iOS"];

    NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:

    [[NSUserDefaults standardUserDefaults] registerDefaults:dic];

    }

    ```

    @“iOS" 為添加的自定義。

三十八、UIPasteboard 屏蔽paste 選項

當UIpasteboard的string 設定為@“” 時,那麼string會成為nil。 就不會出現paste的選項。

三十九、class_addMethod 使用

當 ARC 環境下

class_addMethod([self class], @selector(resolveThisMethodDynamically), (IMP) myMethodIMP, "[email protected]:");

使用的時候@selector 需要使用super的class,不然會報錯。

當MRC環境下

class_addMethod([EmptyClass class], @selector(sayHello2), (IMP)sayHello, "[email protected]:");

可以任意定義。但是系統會出現警告,忽略警告就可以。

四十、AFNetworking 傳送 form-data

将JSON的資料,轉化為NSData, 放入Request的body中。 發送到伺服器就是form-data格式。

四十一、非空判斷注意

BOOL hasBccCode = YES;
if ( nil == bccCodeStr
    || [bccCodeStr isKindOfClass:[NSNull class]] || [bccCodeStr isEqualToString:@""]) { hasBccCode = NO; }
           

如果進行非空判斷和類型判斷時,需要新進行類型判斷,再進行非空判斷,不然會crash。

四十二、iOS 8.4 UIAlertView 鍵盤顯示問題

可以在調用UIAlertView 之前進行鍵盤是否已經隐藏的判斷。

@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) 即我們一般用的簡體中文拼音輸入法,配置好後,再輸入文字時,點選彈出鍵盤上的“小地球”就可以輸入中文了。

如果不行,可以長按“小地球”選擇中文。

四十四、iPhone number pad

phone 的鍵盤類型:

  1. number pad 隻能輸入數字,不能切換到其他輸入
    [紹棠] iOS開發經驗總結
    number_pad.png
  2. phone pad 類型: 撥打電話的時候使用,可以輸入數字和 + * #
    [紹棠] iOS開發經驗總結
    phone_pad.png

四十五、UIView 自帶動畫翻轉界面

- (IBAction)changeImages:(id)sender
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    [UIView beginAnimations:nil context:context]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:
           

四十六、KVO 監聽其他類的變量

[[HXSLocationManager sharedManager] addObserver:self
                                         forKeyPath:@"currentBoxEntry.boxCodeStr"
                                            options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionOld context:nil];
           

在實作的類self中,進行[HXSLocationManager sharedManager]類中的變量@“currentBoxEntry.boxCodeStr” 監聽。

四十七、ios9 crash animateWithDuration

在iOS9 中,如果進行animateWithDuration 時,view被release 那麼會引起crash。

[UIView animateWithDuration:0.25f animations:^{
        self.frame = selfFrame;
    } completion:^(BOOL finished) { if (finished) { [super removeFromSuperview]; } }];
           

會crash。

不會Crash。

四十八、對NSString進行URL編碼轉換

iPTV項目中在删除影片時,URL中需傳送使用者名與影片ID兩個參數。當使用者名中帶中文字元時,删除失敗。

之前測試時,手機号綁定的使用者名是英文或數字。換了手機号測試時才發現這個問題。

對于URL中有中文字元的情況,需對URL進行編碼轉換。

四十九、Xcode iOS加載圖檔隻能用PNG

雖然在Xcode可以看到jpg的圖檔,但是在加載的時候會失敗。

錯誤為 Could not load the "ReversalImage1" image referenced from a nib in the bun

必須使用PNG的圖檔。

如果需要使用JPG 需要添加字尾

五十、儲存全屏為image

CGSize imageSize = [[UIScreen mainScreen] bounds].size;
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 
           

五十一、判斷定位狀态 locationServicesEnabled

這個[CLLocationManager locationServicesEnabled]檢測的是整個iOS系統的位置服務開關,無法檢測目前應用是否被關閉。通過

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的緩存。

// 清理記憶體
[[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 Header View 跟随Tableview 滾動

當tableview的類型為 plain的時候,header View 就會停留在最上面。

當類型為 group的時候,header view 就會跟随tableview 一起滾動了。

五十五、TabBar的title 設定

在xib 或 storyboard 中可以進行tabBar的設定

[紹棠] iOS開發經驗總結

五十五.png

其中badge 是自帶的在圖示上添加一個角标。

1. self.navigationItem.title 設定navigation的title 需要用這個進行設定。

2. self.title 在tab bar的主VC 中,進行設定self.title 會導緻navigation 的title 和 tab bar的title一起被修改。

五十六、UITabBar,移除頂部的陰影

添加這兩行代碼:

頂部的陰影是在UIWindow上的,是以不能簡單的設定就去除。

五十七、當一行中,多個UIKit 都是動态的寬度設定

[紹棠] iOS開發經驗總結

五十七.png

設定horizontal的值,表示出現内容很長的時候,優先壓縮這個UIKit。

五十八、JSON的“<null>” 轉換為nil

使用AFNetworking 時, 使用

AFJSONResponseSerializer *response = [[AFJSONResponseSerializer alloc] init];
response.removesKeysWithNullValues = YES;

_sharedClient.responseSerializer = response;
           

這個參數 removesKeysWithNullValues 可以将null的值删除,那麼就Value為nil了

// END