Search code examples
iosswiftuibuttonuicontrolevents

Subview button is not working


masterBtn.addTarget(self, action: #selector(self.masterBed), for: UIControlEvents.touchUpInside)

i have used above code in subview but it doesn't fire function masterBed. the button within subview is not clickable

Full code:

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")
}

Solution

  • I believe the height and width of the subview remains 0 because the button is not bound to any edges and the button seem to define the height of its superview. You could always check this by settings clipToBounds = true. Its always good to call the lazy if you are using self within an view.

    This should solve your problem:

    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))
    }
    
    @objc func buttonAction() {
        //Do stuff
        }
    }
    

    Slightly unsure about the NSLayoutConstraints, since i use SnapKit or anchorpoints. But i think this should be correct.