Noja Noja - 7 months ago 21
Swift Question

Programmatically created square getting error

I am creating a square programmatically though when i run the app, nothing shows up.

var PB1: UIButton!

func SetUpButton1() {

var PB1: UIButton!
PB1.setBackgroundImage(UIImage(named: "RS"), forState: UIControlState.Normal)
PB1.center = CGPoint(x: 200, y: 200)
PB1.bounds = CGRect(x: 0, y: 0, width: 300, height: 50)

view.addSubview(PB1)

}

Answer

you need to intialize PB1 object with UIButton()

  let PB1 = UIButton()
  PB1.bounds = CGRect(x: 0, y: 0, width: 300, height: 50)

  PB1.setBackgroundImage(UIImage(named: "RS"), forState: UIControlState.Normal)
  PB1.center = CGPoint(x: 200, y: 200)

  self.view.addSubview(PB1)

if you want to detect when is button pressed, you need to call addTarget(...) which Associates a target object and action method with the control.

PB1.addTarget(self, action: #selector(ViewController.buttonPressed(_:)), forControlEvents: .TouchUpInside)

and in your class create function named buttonPressed.

func buttonPressed(sender: UIButton) {
  // do something here
}