The Don
The Don

Reputation: 63

How to programmatically add tags to a UIButton in Swift

I know how to add tags in main.storyboard files, but now I am working on creating everything programmatically. However, I couldn't find anything online that tells me how to add tags to a button. I tried to read the apple documentation but don't know how to implement it.

Here is for example how I created my button, how can I add a tag to it, so that when I make multiple buttons and want to link them to a single action I can know what button has been pressed?

let buttonOne() : UIButton { 
   let button = UIButton(type: .system)
   button.backgroundColor = .red
   return button
}()

Upvotes: 2

Views: 7475

Answers (2)

Murad Al Wajed
Murad Al Wajed

Reputation: 4830

Declare The Button

let menuChooseButton = UIButton()
menuChooseButton.frame.origin.y = 0
menuChooseButton.frame.origin.x = xPosition
menuChooseButton.frame.size.width = subViewWidth
menuChooseButton.frame.size.height = subViewHeight
menuChooseButton.backgroundColor = .clear
menuChooseButton.setTitle("", for: .normal)
menuChooseButton.tag = i
menuChooseButton.addTarget(self, action: #selector(menuSelectAction), for: .touchUpInside)
        menuScrollView.addSubview(menuChooseButton)

Define Button Action

@objc func menuSelectAction(sender: UIButton!){
    var tagNo: Int = sender.tag
    if tagNo == 0{
        // Whatever you want
    }
}

Upvotes: 3

Faysal Ahmed
Faysal Ahmed

Reputation: 7669

Try this:

let buttonOne() : UIButton { 
   let button = UIButton(type: .system)
   button.backgroundColor = .red
   button.tag = 2
   return button
}()

Upvotes: 4

Related Questions