Swift - change the color and size of text when using UIButton

Basically, I have three buttons on the main screen.

When I select one of these buttons, I would like the text on the selected button to change to bold and change color (blue).

When I select another button, I would like the newly selected button to change to bold and change color (blue), and the previously selected button to return to normal. (non-greasy and black text)

I have these buttons sending an action to a script.

This is what I have, I can’t make it work. Help would be greatly appreciated!

@IBAction func buttonOne(sender: UIButton){ sender.setTitleColor(UIColor.blueColor(), forState: UIControlState.Highlighted) } 

I tried .Highlighted and .Selected on UIControlState, it does not seem to work. I also tried the following, but I can't get it to work.

 @IBAction func buttonOne(sender: UIButton){ sender.titleLabel?.textColor = UIColor.blueColor() } 

I realized that since the sender was UIButton, and it was the button that was pressed, removing the values ​​from it, and resetting them will work. I believe something is missing.

thanks

+5
source share
3 answers

It looks like you want UIControlState.Normal

Selected does nothing in most cases, and Highlighted only when a button is pressed. See here for more details: https://developer.apple.com/library/ios/documentation/uikit/reference/uicontrol_class/index.html#//apple_ref/doc/constant_group/Control_State

+4
source

Maybe you can do with conversion ...

 @IBAction func buttonPressed(sender: UIButton) { sender.titleLabel!.textColor = UIColor.blueColor() sender.transform = CGAffineTransformMakeScale(0.8, 0.8) } @IBAction func buttonReleased(sender: UIButton) { sender.titleLabel!.textColor = UIColor.redColor() sender.transform = CGAffineTransformIdentity } 
+2
source

Provide tags to all buttons, connect each button to the same function and try the following code:

@IBAction func butnClicked (sender: UIButton) {

  for tg in 1...2 { print(sender.tag) let tmpButton = self.view.viewWithTag(tg) as? UIButton if tmpButton?.tag == sender.tag { tmpButton?.setTitleColor(.red, for: .normal) } else { tmpButton?.setTitleColor(.gray, for: .normal) } } 

Hope this helps.

0
source

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


All Articles