Noah Iarrobino
Noah Iarrobino

Reputation: 1543

UIButton in UIView subclass not triggering

I am trying to have a button as a subview of this UIView subclass, but the button action is not triggered when clicked, am I doing something wrong here that causes it to not trigger? It's showing the button and everything, but the action isn't working. The custom UIView subclass is nested inside a custom struct

class TakeAvatarView: UIView {
    
    var delegate:SingleTakeDelegate?

    var agree = false

    convenience init(frame: CGRect, agree: Bool, last: Bool) {
        self.init(frame: frame)
        self.agree = agree
        if !last {
            avatarNode()
        } else {
            lastNode()
        }
     }


     func lastNode(){
        let button = UIButton(frame: CGRect(x: 2, y: 2, width: 26, height: 26))
        button.setTitle("+10", for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12)
        button.setTitleColor(.lightGray, for: .normal)
        button.addTarget(self, action: #selector(showMoreTapped), for: .touchUpInside)
        button.isUserInteractionEnabled = true
        self.layer.borderWidth = 1.0
        self.layer.borderColor = UIColor.lightGray.cgColor
        self.addSubview(button)
    }
    
    @objc func showMoreTapped(){
        delegate?.showParticipantsPressed(agree: self.agree)
    }
}

Upvotes: 0

Views: 151

Answers (1)

Muzzle
Muzzle

Reputation: 59

You did everything correctly, make sure that

  1. you call it lastNode()
  2. var delegate:SingleTakeDelegate? is set, you should use weak ref. https://medium.com/macoclock/delegate-retain-cycle-in-swift-4d9c813d0544

I tested your code in playground, it works

Upvotes: 1

Related Questions