要記住的分界是:frame 是相對於父視圖的座標,bounds 是相對於自己的座標。做捲動、縮放動畫時兩者的差異會很明顯。
CGPoint、CGRect 這類結構體在 Objective-C 裡是「值」,直接對它的成員做遞增是不允許的:
// 錯誤
self.iconImage.frame.size.width += 10;
// 正確:必須用暫存變數中轉
CGRect tempFrame = self.iconImage.frame;
tempFrame.size.width += 10;
self.iconImage.frame = tempFrame;
原因是 self.iconImage.frame 回傳的是一份複本,改動複本不會影響原物件,編譯器索性直接禁止這種寫法。
[self.view endEditing:YES];
// 建立
UIButton *btn = [[UIButton alloc] init];
// 加入 view
[self.view addSubview:btn];
// 位置與尺寸
btn.frame = CGRectMake(100, 100, 300, 300);
// 背景圖(不同狀態可給不同圖)
[btn setBackgroundImage:[UIImage imageNamed:@"biaoqingdi"] forState:UIControlStateNormal];
[btn setBackgroundImage:[UIImage imageNamed:@"wangba"] forState:UIControlStateHighlighted];
// 標題
[btn setTitle:@"dianwoa" forState:UIControlStateNormal];
[btn setTitle:@"hah zhentinghua" forState:UIControlStateHighlighted];
// 標題顏色
[btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
// 點擊事件
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
setTitle:、setImage: 這類方法都必須帶 state 參數,這是 UIButton 有別於其他控件的地方,也是新手最常漏掉的細節。
把屬性的初始化放進 getter,等第一次被讀取時才建立,稱為懶載入或延遲載入。重寫 getter 並在其中判斷是否為 nil:
- (NSMutableArray *)dataArray {
if (!_dataArray) {
_dataArray = [NSMutableArray array];
}
return _dataArray;
}
注意要用底端的 ivar(_dataArray)而不是 self.dataArray,否則會造成 getter 無限遞迴。
右鍵專案資料夾 → New File → iOS → Resource → Property List。檔名不要以 info 開頭,以免與系統的 Info.plist 混淆。
NSString *path = [[NSBundle mainBundle] pathForResource:@"imageData.plist" ofType:nil];
_images = [NSArray arrayWithContentsOfFile:path];
plist 讀出來是什麼型別就是什麼型別。一個 NSBundle 代表一個資源資料夾,mainBundle 就是主 App 的資源根目錄。iOS 中所有帶 file 字樣的方法通常都接受完整路徑。
把 numberOfLines 設為 0 即可不限行數換行。若在 storyboard 上看不出效果,可以先把文字塞進去實際執行一次再調整。
// animationImages 接受一個 UIImage 陣列
self.tom.animationImages = images;
self.tom.animationRepeatCount = 1;
self.tom.animationDuration = images.count * 0.1;
[self.tom startAnimating];
// 動畫結束後清空
CGFloat delay = self.tom.animationDuration + 1.0;
[self.tom performSelector:@selector(setAnimationImages:) withObject:nil afterDelay:delay];
用 performSelector:withObject:afterDelay: 排入延遲動作時,會被 target 強引用直到觸發,若在排程期間 target 被釋放反而容易造成物件無法回收,實務上要注意。
NSLog(@"%02d", 1); // 01
%02d 表示輸出兩位數字,不足前面補零。常用在時間與序號格式化。
xib 是輕量級的,描述單一局部介面;storyboard 是重量級的,描述整體畫面之間的跳轉關係。元件需要跨多個畫面重複使用時用 xib,需要呈現完整流程時用 storyboard。