ios – 在Swift中以编程方式添加UIGestureRecognizer到子视图

前端之家收集整理的这篇文章主要介绍了ios – 在Swift中以编程方式添加UIGestureRecognizer到子视图前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我目前有一个子视图,它创建并添加到ViewDidLoad()中的UIView中.我正在尝试使用UIGestureRecognizers来检测点击并取消隐藏特定按钮.我目前的代码
  1. override func viewDidLoad() {
  2. super.viewDidLoad()
  3. architectView = CustomClass(frame: self.view.bounds)
  4. self.view.addSubview(architectView)
  5. let gestureRecognizer = UITapGestureRecognizer(target: self,action: "handleTap:")
  6. gestureRecognizer.delegate = self
  7. architectView.addGestureRecognizer(gestureRecognizer)
  8. }
  9.  
  10. func handleTap(gestureRecognizer: UIGestureRecognizer) {
  11. let alert = UIAlertController(title: "Alert",message: "Message",preferredStyle: UIAlertControllerStyle.Alert)
  12. alert.addAction(UIAlertAction(title: "Click",style: UIAlertActionStyle.Default,handler: nil))
  13. self.presentViewController(alert,animated: true,completion: nil)
  14. }

handleTap()函数是一个简单的测试,用于查看是否正在识别抽头.按下时,此代码不会触发UIAlert?我错过了什么?

解决方法

我在这里测试了你的代码,它确实有效.但是,我认为您可能缺少将UIGestureRecognizerDelegate协议添加到View Controller.见下文:
  1. class ViewController: UIViewController,UIGestureRecognizerDelegate {
  2.  
  3. var architectView = UIView()
  4.  
  5. override func viewDidLoad() {
  6. super.viewDidLoad()
  7. architectView = UIView(frame: self.view.bounds)
  8. self.view.addSubview(architectView)
  9. let gestureRecognizer = UITapGestureRecognizer(target: self,action: "handleTap:")
  10. gestureRecognizer.delegate = self
  11. architectView.addGestureRecognizer(gestureRecognizer)
  12. }
  13.  
  14. func handleTap(gestureRecognizer: UIGestureRecognizer) {
  15. let alert = UIAlertController(title: "Alert",preferredStyle: UIAlertControllerStyle.Alert)
  16. alert.addAction(UIAlertAction(title: "Click",handler: nil))
  17. self.presentViewController(alert,completion: nil)
  18. }
  19.  
  20. override func didReceiveMemoryWarning() {
  21. super.didReceiveMemoryWarning()
  22. // Dispose of any resources that can be recreated.
  23. }
  24.  
  25. }

猜你在找的iOS相关文章