如何根据字符串值检查 UILabel 文本?

How do I check a UILabel text against a string value?

我不是一个很有经验的编码员,所以我很难弄清楚是否可行,如果可行,如何根据给定的字符串值检查标签中找到的字符串。

我希望在 Radius 标签显示 "Radius in feet" 以外的内容并且我的消息文本字段不为空时启用我的添加按钮。

到目前为止我有:

@IBAction func textFieldEditingChanged(sender: UITextField) {
    addButton.enabled = !radiuslabel.text == "Radius in feet" && !messageTextField.text.isEmpty
}

这段代码有误,我一直找不到答案。 Radius 标签从滑块获得信息。 这是滑块功能的代码:

  @IBAction func sliderValueChanged(sender: UISlider) {
    var currentValue = Int(sender.value)
    radiusLabel.text = "\(currentValue)"
}

是否有另一种方法可以将半径保留为整数,同时作为标签的一部分?

试试下面的代码行:

@IBAction func textFieldEditingChanged(sender: UITextField) {
addButton.enabled = (!(radiuslabel.text == "Radius in feet") && !messageTextField.text.isEmpty)
}

希望对您有所帮助...

您不希望 radiusLabel.text 前面的逻辑 NOT (!) 运算符。您反而想使用 "not equal to" 运算符 (!=).

此外,您应该在 UILabel 成员 text 第二次出现时使用可选链接(因为您正在访问成员 isEmpty)。此处与 false 比较,因为它是可选的。

addButton.enabled = radiuslabel.text != "Radius in feet" && messageTextField.text?.isEmpty == false

sender 应该保持类型 UILabel


More about operators in Swift

让我们假设您的滑块的值介于 1 to 102 之间,代表 Feet

中的值

所以根据您的代码,当滑块值更改时,您将在 radiusLabel 中设置值

@IBAction func sliderValueChanged(sender: UISlider) {
    var currentValue = Int(sender.value)
    radiusLabel.text = "\(currentValue)"
}

AND 更改消息标签中的值

@IBAction func textFieldEditingChanged(sender: UITextField) {
    addButton.enabled = !radiuslabel.text == "Radius in feet" && !messageTextField.text.isEmpty
}

您实际上是在 messageTextField 的值更改时启用按钮

您想要的是在滑块值设置为英尺或 messageLabel 具有某个值时立即启用按钮。您需要做的是

func shouldEnableButton()
{
    //Assuming value 2 means value in feet
    addButton.enabled = radiuslabel.text != "2" && (messageTextField.text != nil && !messageTextField.text!.isEmpty)
}

@IBAction func sliderValueChanged(sender: UISlider) {
    var currentValue = Int(sender.value)
    radiusLabel.text = "\(currentValue)"
    messageLbl.text = nil
    self.shouldEnableButton()
}

@IBAction func textFieldEditingChanged(sender: UITextField) {
    self.shouldEnableButton()
}