在Swift中以编程方式将UIGestureRecognizer添加到Subview [英] Adding UIGestureRecognizer To Subview Programmatically in Swift

查看:129
本文介绍了在Swift中以编程方式将UIGestureRecognizer添加到Subview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个子视图,它创建并添加到ViewDidLoad()中的UIView中。我正在尝试使用UIGestureRecognizers来检测点击并取消隐藏特定按钮。我当前的代码:

I currently have a subview that is created and added to the UIView in ViewDidLoad(). I am attempting to user UIGestureRecognizers to detect a tap and unhide a particular button. My current code:

 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?我错过了什么?

The handleTap() function is a simple test to see if the taps are being recognized. This code does not trigger the UIAlert when it is pressed? What am I missing?

推荐答案

我在这里测试了你的代码,它确实有效。但是,我认为您可能会错过将 UIGestureRecognizerDelegate 协议添加到View Controller。见下文:

I tested your code here and it does work. However, I think you might be missing to add the UIGestureRecognizerDelegate protocol to your View Controller. See below:

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", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

这篇关于在Swift中以编程方式将UIGestureRecognizer添加到Subview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆