如何在 UIStackview 上设置点击事件

问题描述 投票:0回答:3

我正在尝试在 UIStackview 上设置单击事件来打开视图控制器。当我这样做时,什么也没有发生。当我点击它时它甚至不打印该行。我在这个网站上尝试了多种解决方案,例如 UITapGestureRecognizer 但无济于事。我做错了什么?

我的代码:

private let stackUIView: UIView = {
     let stackUIView = UIView(frame: CGRect(x: 25, y: 25, width: 400, height: 90))
    let tap = UIGestureRecognizer(target: self, action: #selector(stackviewClicked))
    stackUIView.addGestureRecognizer(tap)
    stackUIView.isUserInteractionEnabled = true
    
    return stackUIView
}()


@objc
    func stackviewClicked() {
        print("UIView Clicked")
        let testVC = testViewController()
        navigationController?.pushViewController(testVC, animated: true)

    }
swift uikit uistackview
3个回答
4
投票

应该是

UITapGestureRecognizer
而不是
UIGestureRecognizer

let tap = UITapGestureRecognizer(target: self, action: #selector(stackviewClicked))

0
投票

对我来说有效,谢谢

termsAndConditionsStack.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(stackviewClicked)))

@objc func stackviewClicked() {
     print("works")
}

0
投票

根据var-as-closure不能引用其他实例变量

要解决这个问题,变量需要改为

private lazy var stackUIView

或者在添加

stackUIView
作为
subview
之前添加手势。

此外,手势

UIGestureRecognizer
需要更改为
UITapGestureRecognizer
,@Shehata Gamal

已经提到过

要了解更多关于手势如何工作的信息,可以关注手势识别器

这是一个示例代码,该解决方案在两种情况下都有效。

 class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(stackviewClicked))
        
        stackUIView.addGestureRecognizer(tapGesture)
        self.view.addSubview(stackUIView)
        self.view.addSubview(stackUIView2)
        
    }
    
    private var stackUIView: UIView = {
        let stackUIView = UIView(frame: CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: 90))
        stackUIView.isUserInteractionEnabled = true
        /**
            // Adding gestures is not working
            //let tap = UITapGestureRecognizer(target: self, action: #selector(stackviewClicked))
            //stackUIView.addGestureRecognizer(tap)
         */
        stackUIView.backgroundColor = .blue
        
        return stackUIView
    }()
    
    
    private lazy var stackUIView2: UIView = {
        let stackUIView = UIView(frame: CGRect(x: 0, y: 300, width: UIScreen.main.bounds.width, height: 90))
        stackUIView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(stackviewClicked))
        stackUIView.addGestureRecognizer(tap)
        
        stackUIView.backgroundColor = .red
        
        return stackUIView
    }()
    
    @objc
    func stackviewClicked() {
        print("UIView Clicked")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.