Link to UIButton value by tag

I know that a pressed button can be updated with a link to the sender. However, I want to access the button from the program body using the link to its tag, and then update its label, if possible. Suggestions on how to do this (in Swift) will be appreciated.

+5
source share
4 answers

To get the button inside the view using your tag, you can use the UIView.viewWithTag function.

 if let button = self.view.viewWithTag(tag) as? UIButton { button.setTitle("newTitle", forState: UIControlState.Normal) } 
+9
source

You must use viewWithTag

Example:

 var button = self.view.viewWithTag(tagNumber) as UIButton button.setTitle("Button Title", forState: UIControlState.Normal) 
+4
source

Swift3: possibly with viewWithTag(button_tag) like:

 let tmpButton = self.view.viewWithTag(tag) as? UIButton tmpButton?.setTitleColor(.red, for: .normal) tmpButton?.setTitle("Button Title", for: .normal) 
+1
source

Set a tag for all buttons. Then we have the property

 var buttons = [UIButton] 

and in your awakeFromNib init it

 buttons.append[myButtonWithTag0] buttons.append[myButtonWithTag1] // etc 

Now you can access your buttons through

 let button = buttons[index] 
0
source

Source: https://habr.com/ru/post/1213224/


All Articles