【问题标题】:Cannot call method of a button from a custom UIView无法从自定义 UIView 调用按钮的方法
【发布时间】:2019-12-02 14:03:59
【问题描述】:

我想从自定义视图中的按钮调用操作。视图本身是 UIViewController 的一部分。但是当我点击视图时,什么也没有发生。我不知道我的错误在哪里,尽管我的代码看起来像 stackoverflow 上的代码。

protocol StoreDelegate: class {
    func didPressButton(_ sender: UIButton)
}

class Store: UIView {

    weak var delegate:StoreDelegate?

    var button: UIButton = {
        let button = UIButton()
        button.setTitle("button", for: .normal)
        button.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        button.backgroundColor = .red
        button.addTarget(self, action: #selector(buttonPress(_:)), for: .touchUpInside)
        return button
    }()

    override init(frame: CGRect) {
        super.init(frame:frame)
        self.addSubview(button)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

   @objc func buttonPress(_ sender: UIButton) {
        delegate?.didPressButton(sender)
        print("here")
    }

}

这是我的 ViewController:

class ViewController: UIViewController, StoreDelegate{

    var testView = Store()

    override func viewDidLoad() {
        super.viewDidLoad()
        testView.delegate = self
        self.view.addSubview(testView)
    }

    func didPressButton(_ sender: UIButton) {
        print("Hello")
    }
}

它既不打印“Hello”也不打印“Here”。也许我误解了协议/委托模式。

【问题讨论】:

    标签: ios swift uibutton delegates protocols


    【解决方案1】:

    您需要为视图设置约束或框架

    testView.frame = ///////
    

    这是接收动作的基础

    【讨论】:

    • 我怎么能错过呢?成功了,非常感谢。
    【解决方案2】:

    您可以在Store 类中实现覆盖sizeToFit 以满足您的需求:

    override func sizeToFit() {
        frame.size = button.frame.size
    }
    

    那么你可以这样称呼它:

    testView.sizeToFit()
    

    您可以考虑使用自动布局以获得更好的尺寸。

    【讨论】:

      猜你喜欢
      • 2019-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-25
      相关资源
      最近更新 更多