UIControl 是所有「可互動控件」的基底類別,建立在 Target-Action 模式之上。它繼承自 UIView,但不應該被直接使用——實務上你會用到的是它的子類別:UIButton、UISlider、UISwitch、UITextField、UISegmentedControl 等等。
Apple 官方文件指出,有兩個理由值得你去擴充 UIControl 子類別:
1. 觀察或修改特定事件的 action 訊息分發
覆寫 sendAction:to:forEvent:,在裡面檢查傳入的 selector、target 物件或 UIControlEvents 位元遮罩,再決定要不要放行。
2. 提供自訂的追蹤行為(例如改變 highlight 的外觀)
覆寫下列一個或多個方法:beginTrackingWithTouch:withEvent:、continueTrackingWithTouch:withEvent:、endTrackingWithTouch:withEvent:。
官方原文如下:
You may want to extend a UIControl subclass for either of two reasons:
· 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:.
以下實作一個效果:使用者必須連續點擊三次,才會真正送出 action。
@interface NYTripleClickControl : UIControl
@property (nonatomic, assign) NSInteger touchTime;
@end
@implementation NYTripleClickControl
- (void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
if (touchTime == 3) {
touchTime = 0;
if ([target respondsToSelector:action]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[target performSelector:action];
#pragma clang diagnostic pop
}
}
}
- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
NSLog(@"%s", __FUNCTION__);
if (++touchTime < 3) {
return NO; // 前兩次不回報追蹤中,因此不會送出 action
}
return YES;
}
- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
NSLog(@"%s", __FUNCTION__);
}
@end
關鍵在 beginTrackingWithTouch:withEvent: 的回傳值。回傳 NO 代表「這次 touch 不算有效的追蹤」,UIControl 後續就不會送出 action;回傳 YES 才會進入 continueTracking 並在抬手時觸發 UIControlEventTouchUpInside。這是 UIControl 追蹤機制的核心。
1. 別用 performSelector 觸發 action。 範例中的 performSelector: 無法傳參數,且會引發 ARC 的編譯警告(因此才需要那三行 pragma 壓掉)。正確做法是走 UIControl 自己的通道:
[super sendAction:action to:target forEvent:event];
這樣做的好處是 target-action 的參數、sender 型別、以及多個 action 的註冊順序都由框架處理,不必自己維護。
2. 自訂控件時記得實作 tracking 方法來控制高亮。 如果只覆寫 drawRect 而不處理 tracking,按下時不會有視覺回饋,使用者會以為沒點到。傳統做法是在 beginTrackingWithTouch: 中設 self.highlighted = YES。
3. 要在 Interface Builder 中使用,記得加上 prepareForInterfaceBuilder。 特別是涉及 IBInspectable 屬性時,否則畫布上不會即時呈現。
4. Swift 中繼承 UIControl 時,記得覆寫 sendAction。 寫法為 override func sendAction(_ action: Selector, to target: Any?, for event: UIEvent?),並在裡面呼叫 super。