【问题标题】:Swift & UIView : How do we add an action to UIView via an extension?Swift & UIView:我们如何通过扩展向 UIView 添加操作?
【发布时间】:2021-12-22 18:24:22
【问题描述】:

在 UIView Extension 中实现时,我无法向我的 UIView 添加操作。

UIView 扩展

extension UIView {
public func addAction(_ selector: Selector) {
        isUserInteractionEnabled = true
        let gesture = UITapGestureRecognizer(target: self, action: selector)
        self.addGestureRecognizer(gesture)
    }
}

ViewController 中的函数

func setAction(_ button: UIView, _ selector: Selector?) {
        button.isUserInteractionEnabled = true
        let gesture = UITapGestureRecognizer(target: self, action: selector)
        button.addGestureRecognizer(gesture)
    }

@objc func hello(){
  print("Hello")
}

我有一个名为 menu 的 UIView 控制器,我希望它在按下它时打印出“Hello”。

如果我执行方法1,我会得到一个错误。

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView hello:]: unrecognized selector sent to instance 0x11fd4ca30'

如果我执行方法 2,它就可以了。

1 - menu.addAction(#selector(hello))

2 - setAction(menu, #selector(hello))

但我可能经常使用它。我们如何通过扩展向 UIView 添加操作?

【问题讨论】:

    标签: ios swift uiview uiviewcontroller extension-methods


    【解决方案1】:

    UIView 类中找不到扩展点击手势hello 方法。

    extension UIView {
    public func addAction(_ selector: Selector, target: AnyObject) {
            isUserInteractionEnabled = true
            let gesture = UITapGestureRecognizer(target: target, action: selector)
            self.addGestureRecognizer(gesture)
        }
    }
    

    addAction方法中添加一个参数作为动作目标。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多