Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selected button color changes

Tags:

swift

uicolor

Can anybody help me in changing the text color when user selected. Like I have three buttons on one viewcontroller and when users taps on 1 button it changes to white and the rest of two become grey.

like image 381
Motivation gym5 Avatar asked Aug 27 '15 03:08

Motivation gym5


2 Answers

You have to do same thing for all buttons in your interfaceBuilder

enter image description here

enter image description here

Then create outlet for all buttons

@IBOutlet weak var button1: UIButton!    
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!

Create action for all buttons

@IBAction func buttonOneAction(sender: AnyObject) {
    button1.selected = true;
    button2.selected = false;
    button3.selected = false;
}

@IBAction func buttonTwoAction(sender: AnyObject) {
    button1.selected = false;
    button2.selected = true;
    button3.selected = false;
}

@IBAction func buttonThreeAction(sender: AnyObject) {
    button1.selected = false;
    button2.selected = false;
    button3.selected = true;
}

output: middle button is selected

enter image description here

like image 73
Shebin Koshy Avatar answered Oct 10 '22 12:10

Shebin Koshy


You'll need to use setTitleColor(_:forState:).

// Setting the color for a button's disabled state to red

button.setTitleColor(UIColor.redColor(), forState: .Disabled)

UIButton Class Reference

like image 34
blerch Avatar answered Oct 10 '22 14:10

blerch