简体   繁体   中英

UIButton in a custom UIView sub class not triggering action events

This has been asked multiple times and I am sorry for that.But I want to get a good deep understanding why it does this. So here is the thing:

ViewController -> customView -> UIButton I am trying to access the button in view controller using delegate/protocols. But before doing all that I want to first make sure that the button triggers the selector methods.

In customView class I have two UIButtons, added targets to them:

   var photoButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Photos", for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.addTarget(self, action: #selector(handleAddPhotoButton), for: .touchUpInside)
    return button
}()

Then in handlePhotoButton (still in custom class) I am saying this:

    @objc func handleAddPhotoButton() {
    print("button")
}

However, it just doesn't work. The constraints are fine. I have checked the heirarchy debugger as well, and the button is on top. In view controller the custom view is initialized like this:

    lazy var accessoryView: AccessoryView = {
    let view = AccessoryView()
    view.delegate = self
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()

My guess is that the view is not being hold on to by self. But what is going wrong here. Please help!

尝试在声明按钮之前添加“懒惰”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM