前言
用過 UIKit 的人都知道,UIButton 天生自帶高亮與點擊回饋,而 UIView 即使掛上了點擊事件,按下去也毫無反應,操作起來就是少了那麼一點「手感」。本文用兩種思路補上這個缺口:一種是用擴充(extension)加上手勢辨識器,另一種是自訂 UIView 子類別去接管觸碰生命週期。
正文
最直覺的做法是透過 extension 包裝一個 UITapGestureRecognizer,讓任何 UIView 都能一行搞定:
extension UIView {
func addOnClickListener(target: AnyObject, action: Selector) {
let gr = UITapGestureRecognizer(target: target, action: action)
gr.numberOfTapsRequired = 1
userInteractionEnabled = true
addGestureRecognizer(gr)
}
}
使用時只要呼叫 view.addOnClickListener(self, action: #selector(handleTap)) 即可,記得別忘了把 userInteractionEnabled 打開,否則手勢永遠不會觸發。
手勢只解決了「有沒有反應」,還沒解決「按下去好不好看」。想要還原 UIButton 那種按下變色、放開還原的體驗,可以繼承 UIView 並覆寫觸碰回呼:
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 透明度」往往更自然;如果是列表項,也可以搭配縮放動畫。重點是把 touchesBegan / touchesEnded / touchesCancelled 三個時機都處理齊全,特別是 touchesCancelled,它對應的是手勢被系統中斷(例如來電、手勢優先)的情況,少了它畫面就會卡在按下的狀態。