【问题标题】:Binary operator '==' cannot be applied to operands of type 'UILabel?' and 'String'二元运算符“==”不能应用于“UILabel”类型的操作数?和“字符串”
【发布时间】:2020-04-30 13:19:24
【问题描述】:

错误:二元运算符“==”不能应用于“UILabel?”类型的操作数和'字符串'


import UIKit

class ViewController: UIViewController {
  let Soft = 5
  let Medium = 8
    let Hard = 12


    @IBAction func hardnessSelected(_ sender: UIButton) {
        let hardness = sender.titleLabel

        if hardness == "Soft"{
            print(Soft)
        }
        else if hardness == "Medium"{
            print (Medium)
        }
        else {
            print (Hard)
        }

    }


}

我该如何解决这个错误?

【问题讨论】:

  • 您认为该错误试图告诉您什么?

标签: swift xcode5


【解决方案1】:

您没有给出错误所在的行号,但查看它提到操作 == 的文本,所以我猜它是其中之一:

if hardness == "Soft"{

else if hardness == "Medium"{

“Soft”和“Medium”是字符串,所以硬度必须是'UILabel?。这些类型无法相互比较。您必须要在按钮上显示文本?查看UILabel docs,有一个text 属性,因此您可能想要更改此行以获取代表按钮文本的字符串:

let hardness = sender.titleLabel.text

您是否使用动态按钮?仅将发件人与您正在检查的按钮进行比较就不太容易出错。将硬编码的字符串与按钮的文本进行比较可能会导致运行时错误。也许您没有正确判断大小写、文本拼写错误或决定稍后进行本地化,因此文本在不同语言中可能会有所不同。这些错误不会在编译时被捕获。

【讨论】:

    【解决方案2】:

    UIButton 通过管理其文本绘制的UILabel 公开其标签。从而改变:

    let hardness = sender.titleLabel
    

    let hardness = sender.titleLabel.text
    

    UIKit docs 说:

    UIButton

    var titleLabel: UILabel?

    显示按钮 currentTitle 属性值的视图。

    和:

    UILabel

    var text: String?

    标签显示的当前文本。

    还有一种更直接的方法是使用currentTitle

    UIButton

    var currentTitle: 字符串?

    按钮上显示的当前标题。

    因此:

    let hardness = sender.currentTitle
    

    也可以。

    【讨论】:

      【解决方案3】:

      UIButton.titleLabel 是一个UILabel,它将其文本存储在UILabel.text 属性中:

      let hardness = sender.titleLabel.text
      

      对于UIButton,您还可以访问UIButton.currentTitle 属性:

      let hardness = sender.currentTitle
      

      【讨论】:

        【解决方案4】:

        您正在尝试比较两种不同的类型。要获取 UILabel 的实际文本,您需要 hardness.text

        【讨论】:

          猜你喜欢
          • 2015-09-10
          • 1970-01-01
          • 2021-03-04
          • 2017-02-13
          • 1970-01-01
          • 1970-01-01
          • 2016-06-30
          • 2015-04-19
          • 1970-01-01
          相关资源
          最近更新 更多