Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a button's text color when tapped

Tags:

swift

uibutton

I'm trying to get a button's text to change font color to red when tapped. I looked at similar posts from months ago and use of that code causes a build error in Xcode 6.1.1. Here is the code I'm trying:

class ViewController: UIViewController {

    @IBAction func firstButton(sender: UIButton) { 
        firstButton.titleLabel.textColor = UIColor.redColor()
    }
}

The error code that I get is:

'(UIButton) -> ()' does not have a member named 'titleLabel'

Any help will be much appreciated as I see Swift as my saving grace after having lost patience in trying to learn Objective C.

like image 467
Carl Spackler Avatar asked Jan 04 '15 01:01

Carl Spackler


2 Answers

For anyone interested in the exact swift code necessary to make this question of mine work, here it is:

class ViewController: UIViewController {

@IBAction func firstButton(sender: UIButton) {

    sender.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)

}
like image 123
Carl Spackler Avatar answered Oct 18 '22 04:10

Carl Spackler


You're trying to change the text color of the function's titleLabel, which doesn't make sense. You should be accessing sender parameter instead if you're trying to get a reference to the button to get at its titleLabel. Additionally, as rakeshbs points out, titleLabel is an optional property of UIButton.

class ViewController: UIViewController {

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

If you break down your error message, you'll realize that this is clearly the issue.

'(UIButton) -> ()' does not have a member named 'titleLabel'

Which states that you are trying to access a member (or property) named titleLabel on an object of type (UIButton) -> (), which means a function that takes a button as input and returns nothing.

like image 8
Mick MacCallum Avatar answered Oct 18 '22 04:10

Mick MacCallum