swiftuibuttonsubviewaddtarget

Swift4 addTarget at UIButton doesnt work in UIView


I programmatically created an UIButton and added it to a subview. AddTarget doesnt work there though. AddTarget only works if I add the button to the mainview.

self.view.addSubview(button)

instead of

ViewSystem.addSubview(button)

Doesnt anyone know why?

Here is the fullcode:

class ViewController: UIViewController {

var ViewSystem = UIView()
@objc func TestPressed(sender: UIButton?) {Test.text=String((sender?.tag)!)

func ButtonCreate () {

    let button = UIButton()
    button.frame = CGRect(x: 50, y: 100, width: 70, height: 70)
    button.addTarget(self, action: #selector(TestPressed), for: .touchUpInside)
    button.backgroundColor = UIColor.red
    button.tag=5
    ViewSystem.addSubview(button)

    self.view.addSubview(ViewSystem)
    }
}

Solution

  • You have to give frame to your ViewSystem. and ViewSystem's height width should be greater than button's X and Y.

        var ViewSystem = UIView()
    ViewSystem.frame = CGRect(x: 50, y: 100, width: 70, height: 70)
    
    @objc func TestPressed(sender: UIButton?) {Test.text=String((sender?.tag)!)
    
    func ButtonCreate () {
    
        let button = UIButton()
        button.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
        button.addTarget(self, action: #selector(TestPressed), for: .touchUpInside)
        button.backgroundColor = UIColor.red
        button.tag=5
        ViewSystem.addSubview(button)
    
        self.view.addSubview(ViewSystem)
        }
    }