我目前有一个子视图,它创建并添加到ViewDidLoad()中的UIView中.我正在尝试使用UIGestureRecognizers来检测点击并取消隐藏特定按钮.我目前的代码:
override func viewDidLoad() { super.viewDidLoad() architectView = CustomClass(frame: self.view.bounds) self.view.addSubview(architectView) let gestureRecognizer = UITapGestureRecognizer(target: self,action: "handleTap:") gestureRecognizer.delegate = self architectView.addGestureRecognizer(gestureRecognizer) } func handleTap(gestureRecognizer: UIGestureRecognizer) { let alert = UIAlertController(title: "Alert",message: "Message",preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Click",style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alert,animated: true,completion: nil) }
handleTap()函数是一个简单的测试,用于查看是否正在识别抽头.按下时,此代码不会触发UIAlert?我错过了什么?
解决方法
我在这里测试了你的代码,它确实有效.但是,我认为您可能缺少将UIGestureRecognizerDelegate协议添加到View Controller.见下文:
class ViewController: UIViewController,UIGestureRecognizerDelegate { var architectView = UIView() override func viewDidLoad() { super.viewDidLoad() architectView = UIView(frame: self.view.bounds) self.view.addSubview(architectView) let gestureRecognizer = UITapGestureRecognizer(target: self,action: "handleTap:") gestureRecognizer.delegate = self architectView.addGestureRecognizer(gestureRecognizer) } func handleTap(gestureRecognizer: UIGestureRecognizer) { let alert = UIAlertController(title: "Alert",preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Click",handler: nil)) self.presentViewController(alert,completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }