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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With