Asim Roy
Asim Roy

Reputation: 10226

How to get the UIButton ID?

I have created 5 buttons dynamically in Swift like this:

for theIndex in 0..<5 {

        let aButton = UIButton()
        aButton.frame = CGRectMake(self.view.bounds.width / 2 - 120, self.view.bounds.height / 2 - 150, 240, 300)
        aButton.setTitle("Button \(theIndex)", forState: .Normal)
        aButton.addTarget(self, action: "btnClicked:", forControlEvents:.TouchUpInside)

        self.view.addSubview(aButton) 
    }

But how can I get the BUTTON_ID for each one?

 func btnClicked(sender: AnyObject?) {
        let vc = storyboard!.instantiateViewControllerWithIdentifier("vc_name") as! DetailVC
        vc.selectedId = **WANT_TO_PASS_BUTTON_ID_HERE**
        self.presentViewController(vc, animated:true, completion:nil)
    }

Upvotes: 0

Views: 3946

Answers (1)

arrteme
arrteme

Reputation: 393

You can use tag property of your buttons (for example, you can set there a button's index), and retrieve it later in func btnClicked(sender: AnyObject?) method to determine a button with which index was pushed

While cycling through your indexes do:

aButton.tag = theIndex

and in btnClicked method do:

vc.selectedId = sender.tag

See for reference Apple docs on UIView

Upvotes: 2

Related Questions