2015-01-04 99 views
9

我试图让按钮的文字在点击时将字体颜色更改为红色。我查看了几个月前的类似帖子,并且使用该代码导致Xcode 6.1.1中出现构建错误。下面是我想要的代码:点击时更改按钮的文字颜色

class ViewController: UIViewController { 

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

错误代码,我得到的是:

'(的UIButton) - >()' 没有一个名为 'titleLabel'

成员

任何帮助将我看到的斯威夫特我的救命之恩试图学习Objective C.

回答

8

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

class ViewController: UIViewController { 

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

如果你打破了你的错误信息,你会意识到这显然是问题所在。

“(的UIButton) - >()”没有一个名为成员“titleLabel”

其中指出您要的对象上访问一个名为titleLabel成员(或属性)键入(UIButton) ->(),这意味着一个将按钮作为输入并不返回任何内容的函数。

+0

这就是问题所在。我没有访问发件人,我试图通过其名称访问该按钮。非常感谢你。 –

14

有兴趣的人所必需的确切SWIFT代码,使矿井工作这个问题,那就是:

class ViewController: UIViewController { 

@IBAction func firstButton(sender: UIButton) { 

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

} 
5

这会为工作斯威夫特3:

yourButton.setTitleColor (UIColor.blue,用于:.normal)

相关问题