做 iOS 開發的人,大概都間接用過 UIControl——最常用的 UIButton 就是它的子類。但很少有項目會直接繼承它。本文把這個類的設計意圖、關鍵屬性與方法梳理清楚,方便你在需要自定義一個「像按鈕一樣」的控件時知道從哪下手。
先看繼承關係:UIControl 繼承自 UIView。官方文檔對它的用途有兩段描述:
To observe or modify the dispatch of action messages to targets for particular events. To do this, override
sendAction:to:forEvent:, evaluate the passed-in selector, target object, or UIControlEvents bit mask, and proceed as required.To provide custom tracking behavior (for example, to change the highlight appearance). To do this, override one or all of the following methods:
beginTrackingWithTouch:withEvent:,continueTrackingWithTouch:withEvent:,endTrackingWithTouch:withEvent:.
翻成人話就是兩件事:一是自定義事件的分發行為,通過重寫 sendAction:to:forEvent: 來決定哪個 selector 在什麼事件下被觸發;二是自定義觸摸跟蹤行為,通過重寫 begin / continue / end 三個 Tracking 方法來控制高亮、按下等交互外觀。想做這兩件事,你必須實現相應的方法——這正是 UIControl 存在的意義:它給 UIView 加上了一套標準化的 target-action 事件模型。
這兩個屬性用來設置控件內部 text 或 image 的水平與垂直位置:
typedef enum {
UIControlContentHorizontalAlignmentCenter = 0,
UIControlContentHorizontalAlignmentLeft = 1,
UIControlContentHorizontalAlignmentRight = 2,
UIControlContentHorizontalAlignmentFill = 3,
} UIControlContentHorizontalAlignment;
typedef enum {
UIControlContentVerticalAlignmentCenter = 0,
UIControlContentVerticalAlignmentTop = 1,
UIControlContentVerticalAlignmentBottom = 2,
UIControlContentVerticalAlignmentFill = 3,
} UIControlContentVerticalAlignment;
Fill 值得特別一提:它會讓內容拉伸填滿整個控件區域,做異形按鈕時經常用到。
從字面就能看出含義,iOS 對狀態的定義是位掩碼,這點很關鍵:
enum {
UIControlStateNormal = 0,
UIControlStateHighlighted = 1 << 0,
UIControlStateDisabled = 1 << 1,
UIControlStateSelected = 1 << 2,
UIControlStateApplication = 0x00FF0000,
UIControlStateReserved = 0xFF000000
};
用位運算而非順序整數,意味著一個控件可以同時處於多個狀態——比如既 highlighted 又 selected。這也是為什麼設置標題、圖片、背景色時都要帶上 state 參數:UIKit 會按狀態位去匹配對應的資源。而 UIControlStateApplication 這段區間是留給開發者自定義狀態用的。
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
三個參數分別是:
target:消息接收者,通常傳 self。
action:一個 SEL,指向要執行的方法,例如 @selector(myMethod:)。
controlEvents:觸發時機,例如 UIControlEventTouchUpInside、UIControlEventValueChanged。它的取值同樣是位掩碼,可以組合多個事件共用一個 handler。
理解了這套機制,你就明白為什麼 UIDatePicker、UISlider、UISwitch 都只需要 target-action 而不用 delegate——它們都是 UIControl 的子類。而 UITableView、UIPickerView 因為交互邏輯複雜得多,走的是 dataSource / delegate 路線。
最近項目中經常要寫這類自定義控件,把這幾個要點記住基本就夠用了:對齊決定外觀排布,state 決定資源匹配,addTarget 決定事件響應。