在 iOS 中,UI 控件大致可分為三大類:
UIControl 本身很少被直接使用,真正常用的是它的子類。它主要負責定義通用接口、為活動控件的事件機制提供實作,當指定動作發生後,控件便會初始化 Action 方法並回呼對應的事件處理方法。
常見方法包括 addTarget:action:forControlEvents:(註冊事件)、removeTarget:action:forControlEvents:(移除事件)、actionsForTarget:forControlEvents:(取得註冊的方法)、allTargets 與 allControlEvents 等。
UI 控件具備多種狀態:普通(Normal)、高亮(Highlighted)、禁用(Disabled) 與 選中(Selected),分別對應 enabled、selected、highlighted 等屬性。此外,beginTrackingWithTouch:withEvent:、continueTrackingWithTouch:withEvent:、endTrackingWithTouch:withEvent: 則對應觸摸的開始、持續與結束。

UIButton 的 Type 屬性決定了按鈕外觀:若要自訂外觀請選擇 Custom;System 為預設風格;Detail Disclosure 顯示 i 圖示;Info Light / Info Dark 顯示說明資訊;Add Contact 則顯示加號按鈕。

在 State Config 中,可為 Default、Highlighted、Selected、Disabled 各狀態分別設定不同的文字、圖片與格式,方法是透過 setTitle:forState:、setTitleColor:forState:、setBackgroundImage:forState:、setImage:forState: 等系列方法,搭配 UIControlState 枚舉值使用。
其他重要屬性還包括 Tittle(文字設定)、Font(字體)、Text Color 與 Shadow Color、Image(圖片按鈕)、Background(背景圖,可讓文字與圖片共存)、Shadow Offset(陰影偏移,水平 > 0 向右、< 0 向左;垂直 > 0 向下、< 0 向上)、Line Break(截斷方式)、Edge(邊界)與 Inset(四周間距)。
UITextField 是單行文字輸入框,重點屬性如下:
UITextView 繼承自 UIScrollView,因此自帶滾動能力,適合用於多行文本。與 UITextField 不同,它沒有繼承 UIControl,無法綁定 IBAction,而是透過 UITextViewDelegate 協定來處理事件,例如 textViewShouldBeginEditing:、textViewDidBeginEditing:、textView:shouldChangeTextInRange:replacementText: 與 textViewDidChange: 等。
由於 UITextView 的虛擬鍵盤右下角是 return(換行)而非 Done,若要關閉鍵盤,常見做法有三種:
resignFirstResponder。inputAccessoryView 設定一個 UIToolbar 作為鍵盤上方的工具列,適合沒有導航列的應用。此外,還可透過 UIMenuController 實作自訂的選取選單,例如在選取文字後顯示「刪除內容」等自訂操作。
UISwitch 是一個開關控件,透過 isOn 判斷當前狀態,並在 Value Changed 事件中做出回應。以下範例展示如何依開關狀態切換背景顏色:
- (IBAction)valueChange:(id)sender {
if ([sender isOn] == YES) {
self.view.backgroundColor = [UIColor whiteColor];
} else {
self.view.backgroundColor = [UIColor blackColor];
}
}
