本文將常見 UIKit 控件與基礎概念整理成開發速查,涵蓋視圖、文字、按鈕、輸入、手勢、列表、導航、提示與計時器等主題。
frame 是相對父視圖的位置與大小,bounds 是自身內容坐標,center 是中心點。常用操作包括 addSubview、insertSubview、bringSubviewToFront、sendSubviewToBack 與 removeFromSuperview。圓角、邊框與背景圖片可透過 layer 設定。
UILabel 可設定文字、字體、顏色、對齊、行數與 lineBreakMode。UIButton 可設定 title、image、背景圖片與點擊事件。UIImageView 可顯示圖片,也能用 animationImages 做簡單輪播。若不想讓系統渲染圖片顏色,可使用 AlwaysOriginal 渲染模式。
UITextField 常見設定包括 placeholder、borderStyle、keyboardType、returnKeyType、secureTextEntry、clearButtonMode 與 leftView。若頁面有多個輸入框,可在需要時收起鍵盤或放棄第一響應者。
常見手勢有點擊、拖拽、縮放、旋轉、長按與輕掃。拖拽與輕掃可能互相衝突,長按可判斷手勢狀態,旋轉與縮放記得在每次處理後還原記錄值。
頁面跳轉可使用 segue、pushViewController、presentViewController。Storyboard 中可透過 performSegueWithIdentifier 觸發,並在 prepareForSegue 中傳遞資料。若需要動態建立頁面,可從 Storyboard 取得 ViewController 後 push 或 present。
UINavigationController 的 navigationBar 可設定背景、色調、透明狀態與標題文字屬性。UIBarButtonItem 可用文字、圖片、系統樣式或自定義視圖建立。UITabBarController 可管理多個頁面,每個頁面可設定 tabBarItem 與 hidesBottomBarWhenPushed。
UIScrollView 可設定 contentSize、contentOffset、回彈與縮放範圍。UITableView 需實現資料源與代理,常用 dequeueReusableCell 重用 Cell,並可處理刪除、插入、移動與索引欄。UICollectionView 則需布局物件,適合網格或自定義排列。
UISearchBar 可與 UISearchDisplayController 搭配,過濾結果。UIToolbar 可放 UIBarButtonItem。UIProgressView 顯示進度,UIActivityIndicatorView 顯示載入中,UIAlertView 與 UIActionSheet 適合簡單提示與選擇。
UISlider 適合數值調整,UISwitch 適合開關,UISegmentedControl 適合分段選擇,UIStepper 適合增減數值,UIWebView 可載入網頁。若只是打開電話、短信、郵件或網頁,也可使用 UIApplication 的 openURL。
NSUserDefaults 適合輕量偏好設定,NSNotificationCenter 適合跨對象廣播,NSTimer 與 performSelector:afterDelay: 適合延時任務。檔案路徑可透過 NSSearchPathForDirectoriesInDomains 取得 Documents、Library 與 Caches 等目錄。