UIView 不像 UIButton,加了點擊事件並不會自帶按下回饋,用起来總覺得少了點什麼。下面分別用擴展與子類兩種方式補上這個體驗。
extension UIView { func addOnClickListener(target: AnyObject, action: Selector) { let gr = UITapGestureRecognizer(target: target, action: action) gr.numberOfTapsRequired = 1 userInteractionEnabled = true addGestureRecognizer(gr) } }
這裡有個關鍵行:userInteractionEnabled = true。UIImageView 和 UILabel 預設是 false,不加這句,手勢永遠不會觸發——很多人卡在这一步懷疑代碼寫錯。
class UIViewEffect : UIView { override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { backgroundColor = UIColor.groupTableViewBackgroundColor() } override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { UIView.animateWithDuration(0.15, animations: { () -> Void in self.backgroundColor = UIColor.clearColor() }) } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { UIView.animateWithDuration(0.15, animations: { () -> Void in self.backgroundColor = UIColor.clearColor() }) } }
效果可以自己換。若基底類是 UIImageView,改成按下時降低 alpha 往往更自然;如果是純文字區域,換底色是最直白的選擇。touchesCancelled 一定要一起處理,否則使用者的手指滑出邊界後,高亮狀態會一直掛在那裡。