Rising
Rising

Reputation: 2555

Changing color of button text and state

I need to change the color of my button's text. I also need to change the state to Disabled after the user presses it.

I have no idea how to do this. I've been looking things up for a while but they're all either in objective C or I can't understand it (usually help docs, they're stupid.).

Upvotes: 22

Views: 67298

Answers (4)

Paradisiak
Paradisiak

Reputation: 821

In swift you change color for a specific State with the setTitleColor method.

In you case it will be :

button.setTitleColor(UIColor.grayColor, forState: UIControlState.Normal)

Swift 5 Update:

button.setTitleColor(UIColor.grayColor, for: UIControl.State.normal)

Upvotes: 82

JaspreetKour
JaspreetKour

Reputation: 837

For Swift3, try below code :

 @IBAction func butnClicked(sender : UIButton) {
     sender.setTitleColor(.red, for: .normal)
     sender.isEnabled = false
 }

Set Enabled and text color from story board.

enter image description here

Upvotes: 5

MikeJ
MikeJ

Reputation: 2437

Swift 3

button.setTitleColor(UIColor.gray, for: UIControlState.normal)

Note that;

  • grayColor has been renamed to gray
  • Normal is now normal (lowercase)

You have to set the text colour for the specific button state.

Upvotes: 23

Avi
Avi

Reputation: 2216

To change color of text

button.titleLabel.textColor = UIColor.grayColor()

To change state, on button press add following -

button.enabled = true

IBAction method should be like -

@IBAction func buttonTapped(sender : UIButton!) {
    sender.enabled = false
}

Upvotes: 36

Related Questions