【问题标题】:Changing a button's text color when tapped点击时更改按钮的文本颜色
【发布时间】:2015-01-04 01:52:40
【问题描述】:

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

class ViewController: UIViewController {

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

我得到的错误代码是:

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

任何帮助都将不胜感激,因为我在尝试学习 Objective C 时失去了耐心,将 Swift 视为我的救命稻草。

【问题讨论】:

    标签: swift uibutton


    【解决方案1】:

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

    class ViewController: UIViewController {
    
    @IBAction func firstButton(sender: UIButton) {
    
        sender.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
    
    }
    

    【讨论】:

      【解决方案2】:

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

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

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

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

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

      【讨论】:

      • 这就是问题所在。我没有访问发件人,我试图通过其名称访问按钮。非常感谢。
      【解决方案3】:

      这适用于 Swift 3:

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

      【讨论】:

        【解决方案4】:

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

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

        请阅读 swift optionals 以详细了解这一点。 http://www.appcoda.com/beginners-guide-optionals-swift/

        【讨论】:

          猜你喜欢
          • 2021-01-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-28
          • 2021-07-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多