子视图按钮不起​​作用

Rus*_*kar 0 uibutton ios uicontrolevents swift

masterBtn.addTarget(self, action: #selector(self.masterBed), for: UIControlEvents.touchUpInside)
Run Code Online (Sandbox Code Playgroud)

我在子视图中使用了上面的代码,但它没有触发功能masterBed。子视图中的按钮不可点击

完整代码:

let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button.setTitleColor(.gray, for: .normal)
button.center = CGPoint(x: 380, y: 110)
button.setTitle(">", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.addSubview(button)

func buttonAction () {
    print("button pressed")
}
Run Code Online (Sandbox Code Playgroud)

Vol*_*lan 5

我相信子视图的高度和宽度保持为 0,因为按钮没有绑定到任何边缘并且按钮似乎定义了其超级视图的高度。您始终可以通过设置 clipToBounds = true 来检查这一点。如果您在视图中使用 self,那么调用惰性总是好的。

这应该可以解决您的问题:

class buttonView: UIView {
private lazy var button: UIButton = {
    let button = UIButton()
    button.setTitleColor(.gray, for: .normal)
    button.setTitle("MyButton", for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    return button
}()

override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}

func setup() {
    addSubview(button)

    addConstraint(NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 10))
    addConstraint(NSLayoutConstraint(item: button, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 10))
    addConstraint(NSLayoutConstraint(item: button, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0))
    addConstraint(NSLayoutConstraint(item: button, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0))
    addConstraint(NSLayoutConstraint(item: button, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 80))
    addConstraint(NSLayoutConstraint(item: button, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 35))
}

func buttonAction() {
    //Do stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

有点不确定 NSLayoutConstraints,因为我使用 SnapKit 或锚点。但我认为这应该是正确的。