ios – 在Swift中以编程方式添加UIGestureRecognizer到子视图
2020年01月16日
作者:佚名
我目前有一个子视图,它创建并添加到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. } }
以上是来客网为你收集整理的ios – 在Swift中以编程方式添加UIGestureRecognizer到子视图全部内容,希望文章能够帮你解决ios – 在Swift中以编程方式添加UIGestureRecognizer到子视图所遇到的程序开发问题。
如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。