2015-01-04 145 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)

相關問題