Bhuwan Sharma
Bhuwan Sharma

Reputation: 269

How to create a UIButton programmatically

I am trying to build UIViews programmatically. How do I get a UIButton with an action function in Swift?

The following code does not get any action:

let btn: UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
btn.backgroundColor = UIColor.greenColor()
btn.setTitle("Click Me", forState: UIControlState.Normal)
btn.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(buttonPuzzle)

The following selector function is:

func buttonAction(sender: UIButton!) {
    var btnsendtag: UIButton = sender
}

Upvotes: 20

Views: 34374

Answers (3)

Want Query
Want Query

Reputation: 1426

You're just missing which UIButton this is. To compensate for this, change its tag property.
Here is you answer:

let btn: UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
btn.backgroundColor = UIColor.greenColor()
btn.setTitle("Click Me", forState: UIControlState.Normal)
btn.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
btn.tag = 1               // change tag property
self.view.addSubview(btn) // add to view as subview

Swift 3.0

let btn: UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
btn.backgroundColor = UIColor.green
btn.setTitle(title: "Click Me", for: .normal)
btn.addTarget(self, action: #selector(buttonAction), forControlEvents: .touchUpInside)
btn.tag = 1               
self.view.addSubview(btn)

Here is an example selector function:

func buttonAction(sender: UIButton!) {
    var btnsendtag: UIButton = sender
    if btnsendtag.tag == 1 {            
        //do anything here
    }
}

Upvotes: 34

Abizern
Abizern

Reputation: 150715

Using a tag is a fragile solution. You have a view and you are creating and adding the button to that view, you just need to keep a reference to it: For example

In your class, keep a reference to the button

var customButton: UIButton!

Create the button and set the reference

let btn = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
btn.backgroundColor = .greenColor()
btn.setTitle("Click Me", forState: .Normal)
btn.addTarget(self, action: #selector(MyClass.buttonAction), forControlEvents: .TouchUpInside)
self.view.addSubview(btn)
customButton = btn

Test against this instance in the action function

func buttonAction(sender: UIButton!) {
    guard sender == customButton else { return }

    // Do anything you actually want to do here
}

Upvotes: 9

Laxman Ghimire
Laxman Ghimire

Reputation: 87

You have to addSubview and tag on that btn.

Upvotes: 1

Related Questions