Search code examples
swiftswift4

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
}()

Solution

  • Try this:

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