0

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)
    }
}
Andy
  • 185
  • 1
  • 13

2 Answers2

3

This happening because you are set your button frame graterthen your view that's why your button not tapped.

you are not set your view frame and then how you can you set your button inside your view.

Here I update your ButtonCreate () function code it's working nicely.

func ButtonCreate () {
            ViewSystem.frame = CGRect(x: 50, y: 100, width: 200, height: 70)
            ViewSystem.backgroundColor = .blue
            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.clipsToBounds = false
            ViewSystem.addSubview(button)

            self.view.addSubview(ViewSystem)
        }

I hope it's helpfull for you and save your time

Berlin
  • 2,115
  • 2
  • 16
  • 28
1

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)
    }
}
Ajay saini
  • 2,352
  • 1
  • 11
  • 25