简体   繁体   English

点击时更改按钮的文本颜色

[英]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. 我查看了几个月前的类似帖子,使用该代码会导致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' '(UIButton) - >()'没有名为'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. 任何帮助将非常感激,因为我在尝试学习Objective C后失去耐心,因此我认为Swift是我的拯救恩典。

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. 您正在尝试更改函数titleLabel的文本颜色,这没有意义。 You should be accessing sender parameter instead if you're trying to get a reference to the button to get at its titleLabel . 如果您尝试获取对按钮的引用以获取其titleLabel则应该访问sender参数。 Additionally, as rakeshbs points out, titleLabel is an optional property of UIButton. 另外,正如rakeshbs指出的那样, titleLabel是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' '(UIButton) - >()'没有名为'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. 这表明您试图在类型(UIButton) -> ()的对象上访问名为titleLabel的成员(或属性(UIButton) -> () ,这意味着一个函数将按钮作为输入并且不返回任何内容。

this will work for Swift 3 : 这适用于Swift 3:

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

UIButton.titlelabel is an optional property. UIButton.titlelabel是一个可选属性。 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. 请阅读有关swift选项的详细信息。 http://www.appcoda.com/beginners-guide-optionals-swift/ http://www.appcoda.com/beginners-guide-optionals-swift/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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