您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

Swift 2.1 實作:讓 UIView 也有點擊事件與按下回饋

編輯:iOS 開發綜合

前言

UIView 不像 UIButton,加了點擊事件並不會自帶按下回饋,用起来總覺得少了點什麼。下面分別用擴展與子類兩種方式補上這個體驗。

一、為 UIView 添加點擊事件

 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,不加這句,手勢永遠不會觸發——很多人卡在这一步懷疑代碼寫錯。

二、為 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 往往更自然;如果是純文字區域,換底色是最直白的選擇。touchesCancelled 一定要一起處理,否則使用者的手指滑出邊界後,高亮狀態會一直掛在那裡。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved