【问题标题】:How do you fix the error "cannot assign value"?您如何解决“无法赋值”的错误?
【发布时间】:2018-07-10 09:45:22
【问题描述】:

我只是在学习 swift 基础知识,并认为尝试使用我的技能并出现问题是个好主意。我已经尝试了所有我知道有人可以帮助的东西。下面是我的图片。

【问题讨论】:

  • UIButton 那是类,而不是对象。你的意思是number.title 另外,复制/粘贴代码不是截图。但这不是您更新 UIButton 标题的方式,请使用 setTitle:forState
  • 首先,我建议您将代码添加为 sn-p 而不是屏幕截图。
  • @Larme 我将粘贴我的代码,但我这样做了,但遇到了同样的问题。
  • @vadian 谢谢。

标签: ios swift


【解决方案1】:

首先请发文字,不要发图片

您必须使用 (IBOutlet) 实例 number 而不是类型 UIButton,并且您必须使用正确的 API

number.setTitle(String(score), for: .normal)

但在IBAction 中,我会使用静态sender 类型(而不是未指定的Any)声明方法并使用它

@IBAction func touched(_ sender : UIButton) {
    score += 1
    sender.setTitle(String(score), for: .normal)
}

【讨论】:

  • 你比我早 10 秒发帖 :)
【解决方案2】:

如果你想改变一个按钮的标题,你需要这样做:

  • button_Outlet_Name.setTitle(title: String?, for: UIControlState) 或
  • button_Outlet_Name.title.text = "新标题"

请记住在您的按钮 OUTLET 上执行此操作,而不是在 UIButton 类上执行此操作

【讨论】:

    【解决方案3】:

    你不能那样改变你的按钮的标题,你在那里写的东西

    UIButton.title = String(score)
    

    这意味着您正在调用UIButton 类的静态方法,并且该方法的名称是title

    如果您想更改按钮的位置,可以通过以下方式进行:

    第 1 步:通过 ctrl+拖动来引用您的按钮。

    第 2 步:在您的 IBAction 中您需要写:

    yourButton.setTitle("\(score)", for: .normal)
    

    【讨论】:

      【解决方案4】:

      在这里,您正在访问 UIButton 类的静态方法。如果要设置标题,则需要在实例上进行。 根据您所拥有的,在 IBAction 中,您可以将发件人转换为 UIButton,然后设置标题。您也可以为特定状态执行此操作,因为标题与 UIButton 的状态密切相关。

      if let btn = sender as? UIButton {
          btn.setTitle(“\(score)”, forState: .normal)
      }
      

      您也可以改用 IBOutlet 引用。

      number.setTitle(“\(score)”, forState: .normal)
      

      每当您在字符串中使用\(variable) 时,它都会使用要在字符串中显示的变量的字符串值。

      【讨论】:

        【解决方案5】:

        我不确定你想做什么,但如果你想更改点击按钮的标题,你可以这样做:

        @IBAction func touched(_ sender: Any) {
            score += 1
            // check if the sender is UIButton
            if let button = sender as? UIButton {
                //change your button title
                button.setTitle("\(scroe)", for: UIControlState.normal)
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-29
          • 1970-01-01
          相关资源
          最近更新 更多