简体   繁体   中英

Changing a button's text color when tapped

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.

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)

}

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.

this will work for Swift 3 :

yourButton.setTitleColor(UIColor.blue, for: .normal)

UIButton.titlelabel is an optional property. You have to use optional chaining for changing its properties.

firstButton.titleLabel?.backgroundColor = UIColor.redColor()

Please read about swift optionals to understand this in detail. http://www.appcoda.com/beginners-guide-optionals-swift/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM