本文整理了一批 iOS 開發中經常遇到的基礎細節與常用寫法,方便日後快速查閱:
1. 不可變陣列轉為可變陣列、從陣列取數據;2. 獲取字串長度;3. 隱藏單個視圖所屬控制器的導航條;4. 邊帽法拉伸圖片;5. 監聽系統通知;6. 以字串繪製矩形;7. 視圖層級切換與可交互性;8. 二進位數據型別轉換;9. 刪除視圖上所有子視圖;10. 將視圖置於最前;11. 頁面跳轉(push/pop、present/dismiss);12. 將資料庫檔案拷貝進沙盒;13. 直接加載網頁;14. 結構體轉字串輸出;15. 角度轉弧度、橢圓座標計算;16. 前向引用 @class;17. center + bounds = frame;18. 查詢父視圖;19. 重新加載 xib;20. 獲取觸摸對象;21. 判斷對象關係的常用屬性;22. 獲取系統當前時間;23. 分割與拼接字串、去空格;24. 定時器與延遲加載;25. 結束編輯收起鍵盤;26. 保存圖片到相冊;27. 輸出當前方法名;28. 三元運算符;29. 從陣列隨機取數據;30. 視圖修剪、透明度、隱藏與移除;31. 字串拼接輸出控件屬性;32. 第一響應者;33. 導航控制器相關;34. 彈框;35. 九宮格;36. 布爾判斷輸出;37. 去除換行符;38. URL 中文編碼;39. 讀取沙盒某資料夾全部內容;40. 讀取檔案屬性;41. 設置 description 輸出格式;42. 沙盒路徑查找便捷法;43. 對象序列化與歸檔;44. 強制數據即刻入沙盒、NSUserDefaults 存取;45. 判斷路徑是否存在檔案;46. 網絡超時設置;47. 單元格關鍵控件;48. 按鈕失去響應;49. URL 特殊字符編碼;50. 圖片轉二進位;51. 斷點下載屬性;52. base64 與 MD5 加解密;53. 截取請求體字段;54. 判斷授權 token 與過期;55. 枚舉設置多個 tag;56. 向上取整;57. 查找具體檔案路徑;58. 導航條加控件;59. 視圖留白;60. 漢字轉拼音;61. 設備寬高宏定義;62. 按鈕背景圖防變形;63. 異常捕獲處理;64. 去除首尾空白與換行;65. 自定義視圖矩形;66. 根據圖片設置按鈕大小。
以下挑選部分常用片段說明。
1. 不可變陣列轉可變陣列
NSArray * arr = @[@"人在囧途",@"煎餅俠",@"西游記",];
NSMutableArray * arr = [NSMutableArray arrayWithArray:arr];
2. 獲取字串長度(寬度)
NSString * str = nameLabel.text;
CGSize size = [str sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17]}];
此時 size.width 即為字串寬度。
3. 隱藏某視圖所屬控制器的導航條
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self.navigationController setNavigationBarHidden:YES];
}
4. 邊帽法拉伸圖片(複製某像素、其餘不變,拉伸後變形小)
UIImage * image = [[UIImage imageNamed:@"bubble.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:20];
bubbleImageView.image = image;
5. 監聽系統通知(以鍵盤 frame 變化為例)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(KeyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
-(void)KeyboardWillChangeFrame:(NSNotification *)noti
{
NSDictionary * dic = noti.userInfo;
float time = [[dic objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
int curve = [[dic objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
CGRect rect = [[dic objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
}
6. 以字串繪製矩形(MAXFLOAT 代表無限)
CGRect rect = [str boundingRectWithSize:CGSizeMake(200, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15]} context:nil];
7. 視圖層級切換與可交互性
[self.window exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
要點:父視圖不可交互時,其子視圖也不可交互;父視圖可交互時,子視圖可交互性由自身決定。關鍵屬性:userInteractionEnabled。
8. 二進位數據與字串互轉
NSString * data1 = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString * str2 = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
圖片轉二進位:NSData * data = UIImageJPEGRepresentation(image, 1);
9. 刪除視圖上所有子視圖
NSArray * arr = _scrollerView.subviews;
for (UIImageView * imageView in arr) {
[imageView removeFromSuperview];
}
10. 將視圖置於最前
[self.view bringSubviewToFront:_tableView];
11. 頁面跳轉(需找 window)
UIWindow * window = [[[UIApplication sharedApplication] delegate] window];
window.rootViewController = aViewController;
導航控制器:popViewControllerAnimated 返回上一頁;popToRootViewControllerAnimated 返回根視圖;present/dismiss 模態彈出與消失。
12. 將資料庫拷貝到沙盒
NSString * sourePath = [[NSBundle mainBundle] pathForResource:@"database" ofType:@"sqlite"];
if (![[NSFileManager defaultManager] fileExistsAtPath:[self filePath]]) {
[[NSFileManager defaultManager] copyItemAtPath:sourePath toPath:[self filePath] error:nil];
}
13. 加載網頁
NSURL * url = [NSURL URLWithString:@"https://www.baidu.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
或用 [[UIApplication sharedApplication] openURL:url] 直接開啟。
14. 結構體轉字串輸出
NSLog(@"-------%@", NSStringFromCGRect(rect));
15. 角度轉弧度
#define ANGLE_2_HUDU(X) (X)*M_PI/180.0
float x = 160 + 100 * cos(ANGLE_2_HUDU(btn.angle));
float y = 240 + 100 * sin(ANGLE_2_HUDU(btn.angle));
16. 前向引用 @class
為避免交叉導入,可用 @class 提前告知編譯器該類存在,真正使用時再在 .m 中 #import 對應頭檔。
17. center + bounds = frame
image.center = CGPointMake(160, 120);
image.bounds = CGRectMake(0, 0, 160, 120);
18. 查詢父視圖與子視圖
NSLog(@"==%@", image.superview);
NSLog(@"==%@", self.window.subviews);
19. 重新加載 xib
ViewController * vc = [[ViewController alloc] initWithNibName:@"Empty" bundle:nil];
20. 獲取觸摸對象
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [touches anyObject];
CGPoint point = [touch locationInView:self.view];
if (CGRectContainsPoint(_mainPlane.frame, point)) {
_mainPlane.center = point;
}
}
21. 判斷對象關係的常用方法
CGRectContainsPoint 判斷矩形是否包含某點;CGRectIntersectsRect 判斷兩矩形是否相交;isEqualToString 判斷字串相等;length 取字串長度。
22. 獲取系統當前時間
NSDate * date = [NSDate date];
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yy-MM-dd HH-mm-ss"];
NSString *str = [formatter stringFromDate:date];
(年 yyyy、月 MM、日 dd、時 HH、分 mm、秒 ss)
23. 分割與拼接字串
NSArray * arr = [str componentsSeparatedByString:@" "];
去掉中間空格:[self stringByReplacingOccurrencesOfString:@" " withString:@""];
去首尾空白與換行:[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
24. 定時器與延遲加載
開啟前先判斷是否已存在,避免重複:
if (_timer) { return; }
_timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
關閉時:[_timer invalidate]; _timer = nil;
延遲執行:[self performSelector:@selector(參數) withObject:nil afterDelay:5];
25. 結束編輯收起鍵盤
[self.window endEditing:YES];
26. 保存圖片到相冊
UIImageWriteToSavedPhotosAlbum([UIImage imageNamed:@"20.jpg"], self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
27. 輸出當前方法名
NSLog(@"%s", __func__);
28. 三元運算符
number = i <= 8 ? (i + 1) : 0;
29. 從陣列隨機取數據
int random = arc4random() % numberArray.count;
int number = [numberArray[random] intValue];
[numberArray removeObjectAtIndex:random];
30. 視圖修剪、透明度、隱藏與移除
bigView.clipsToBounds = YES;
bigView.layer.cornerRadius = 90; bigView.layer.masksToBounds = YES;
_view.alpha = 0;
[_view removeFromSuperview];
33. 導航控制器相關
設置導航條背景色應用 barTintColor 而非 backgroundColor;標題用 self.title;左右欄用 self.navigationItem.leftBarButtonItem / rightBarButtonItem;隱藏用 setNavigationBarHidden:。
34. 彈框(UIAlertView / UIActionSheet)
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"新建聯系人" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil];
alertView.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
[alertView show];
(ActionSheet 不可在 viewDidLoad 中創建,因其展示於 self.view 上。)
35. 九宮格(單層 for 循環)
for (int a = 0; a < 9; a++) {
float jiange = (320 - 40 * 3) / 4;
int x = a % 3; int y = a / 3;
UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
btn.frame = CGRectMake(jiange + (40 + jiange) * x, jiange + (40 + jiange) * y, 40, 40);
[self.view addSubview:btn];
}
43. 對象序列化與歸檔
步驟:建立 NSMutableData → 用 NSKeyedArchiver 歸檔 → encodeObject:forKey: 編碼 → finishEncoding 收尾 → writeToFile 寫入沙盒。反序列化則用 NSKeyedUnarchiver 讀取解碼。自訂類別需遵循 NSCoding 協議並實作 encodeWithCoder: 與 initWithCoder:。
44. NSUserDefaults 存儲輕量級數據
[[NSUserDefaults standardUserDefaults] setObject:_nameField.text forKey:@"name"];
[[NSUserDefaults standardUserDefaults] synchronize];
取值:[[NSUserDefaults standardUserDefaults] objectForKey:@"name"];
51. 圖片轉二進位
NSData * data = UIImageJPEGRepresentation(self.imageView.image, 0.00001);
(PNG 體積接近原圖,JPG 可壓縮。)
52. 斷點下載要點
[request addValue:[NSString stringWithFormat:@"bytes=%lld-", _receiveSize] forHTTPHeaderField:@"Range"];
寫入時 [_fileHandle seekToEndOfFile]; [_fileHandle writeData:data];
進度 = 已接收 / 總大小。
53. base64 與 MD5
_nameField.text base64EncodedString 編碼;base64DecodedString 解碼;_pswField.text MD5 加密。
56. 用枚舉設置多個 tag
typedef NS_ENUM(NSInteger, RequestType) {
GetTokenRequestTag = 0,
GetStatusListRequestTag
};
對象.tag = GetTokenRequestTag;
60. 漢字轉拼音
CFStringTransform(hanziRef, 0, kCFStringTransformMandarinLatin, NO);
CFStringTransform(hanziRef, 0, kCFStringTransformStripDiacritics, NO);
61. 設備寬高宏定義
#define DEVICE_WIDTH [UIScreen mainScreen].bounds.size.width
#define DEVICE_HEIGHT [UIScreen mainScreen].bounds.size.height
63. 異常捕獲處理
在 AppDelegate 中綁定 NSSetUncaughtExceptionHandler(&getException);,於崩潰時把 exception 的 name、reason、callStackSymbols 等資訊寫入檔案,供下次啟動回報伺服器。
64. 去除首尾空白與換行
headerData = [headerData stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
headerData = [headerData stringByReplacingOccurrencesOfString:@"\r" withString:@""];
headerData = [headerData stringByReplacingOccurrencesOfString:@"\n" withString:@""];