繁体   English   中英

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

[英]Changing a button's text color when tapped

我试图获取一个按钮的文本,在点击时将字体颜色更改为红色。 我查看了几个月前的类似帖子,使用该代码会导致Xcode 6.1.1中出现构建错误。 这是我正在尝试的代码:

class ViewController: UIViewController {

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

我得到的错误代码是:

'(UIButton) - >()'没有名为'titleLabel'的成员

任何帮助将非常感激,因为我在尝试学习Objective C后失去耐心,因此我认为Swift是我的拯救恩典。

对于任何对使我的工作问题所需的确切快速代码感兴趣的人,这里是:

class ViewController: UIViewController {

@IBAction func firstButton(sender: UIButton) {

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

}

您正在尝试更改函数titleLabel的文本颜色,这没有意义。 如果您尝试获取对按钮的引用以获取其titleLabel则应该访问sender参数。 另外,正如rakeshbs指出的那样, titleLabel是UIButton的可选属性。

class ViewController: UIViewController {

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

如果您分解错误消息,您将意识到这显然是问题所在。

'(UIButton) - >()'没有名为'titleLabel'的成员

这表明您试图在类型(UIButton) -> ()的对象上访问名为titleLabel的成员(或属性(UIButton) -> () ,这意味着一个函数将按钮作为输入并且不返回任何内容。

这适用于Swift 3:

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

UIButton.titlelabel是一个可选属性。 您必须使用可选链接来更改其属性。

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

请阅读有关swift选项的详细信息。 http://www.appcoda.com/beginners-guide-optionals-swift/

暂无
暂无

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

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