AyBayBay
AyBayBay

Reputation: 1724

How to change the text color of a UIButton on iOS when selected and keep it selected

I have a very minimal UIButton (no border, white text color on a clear background, its superView has a dark background). When a user taps the UIButton, I change the alpha channel of the white text color to give it that greyed out look and signal to the user they actually pressed it. Now how do I keep the button in a selected state after they have pressed the button?

The textColor almost instantaneously switches back from gray to white, and I want the color to stay gray, almost behave "stickily" so the user really sees it was selected. How do I achieve this? This is the code I have so far.

logInButton.setTitleColor(pwStyle.appThemeTextFontColor, for: .normal)
        logInButton.setTitleColor(pwStyle.appThemeTextFontColor.withAlphaComponent(0.3), for: .highlighted)
        logInButton.setTitleColor(pwStyle.appThemeTextFontColor.withAlphaComponent(0.3), for: .selected)

^^ Above pwStyle.appThemeTextFontColor just returns UIColor.white

Upvotes: 0

Views: 824

Answers (2)

agibson007
agibson007

Reputation: 4373

Make sure the button type is Custom instead of System so the title does not fade out and use this in your touch up inside.

   @IBAction func myButtonDidPress(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected

    }

Cheers

Upvotes: 0

Florian Chrometz
Florian Chrometz

Reputation: 445

You could add the "selected" color to the "disabled" button state:

logInButton.setTitleColor(pwStyle.appThemeTextFontColor.withAlphaComponent(0.3), for: .disabled)

and simply disable the button on press.. and re-enable it at some later point.

Upvotes: 0

Related Questions