簡體   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