【问题标题】:Swift: UITextField IBAction - EditingChanged - Button stays enabled, even though textfield values are changed?Swift:UITextField IBAction - EditingChanged - 按钮保持启用,即使文本字段值已更改?
【发布时间】:2014-11-20 22:41:14
【问题描述】:

当两个不同的文本字段的 EditingChanged 时,我有两个 IBAction。在这些方法中,我有一个 if 语句,如果两个 UITextField 都包含整数,则启用一个按钮。问题是,当按钮启用时,它保持启用状态,即使我编辑文本字段并更改它们,使它们除了整数之外还有字符。我该如何解决?提供代码时请彻底清晰,因为我是编程新手。如果您想知道,这是我目前拥有的代码:

@IBAction func calorieNumberEditingChanged(sender: AnyObject) {
    // If both variables are true and the text fields contain integers, enable button
    if self.yourWeightFilled && self.calorieNumberFilled {
        self.calculateButton.enabled = true
    }
}
@IBAction func yourWeightEditingChanged(sender: AnyObject) {
    // If both variables are true and the text fields contain integers, enable button
    if self.yourWeightFilled && self.calorieNumberFilled {
        self.calculateButton.enabled = true
    }
}

【问题讨论】:

    标签: ios if-statement swift uibutton edit


    【解决方案1】:

    这与 Evan 的回答类似,但我们可以简化代码。

    func validateCalculateButton() {
        self.calculateButton.enabled = 
            (self.yourWeightFilled && self.calorieNumberFilled)
    }
    
    @IBAction func calorieNumberEditingChanged(sender: AnyObject) {
        self.validateCalculateButton()
    }
    
    @IBAction func yourWeightEditingChanged(sender: AnyObject) {
        self.validateCalculateButton()
    }
    

    确实,这里不需要两个单独的@IBAction 方法。您可以将两个 UI 元素链接到同一个方法中,除非您需要对未包含在此处发布的代码中的每个元素执行单独的操作。

    【讨论】:

      【解决方案2】:

      尝试添加 else 语句并将它们改回未启用。

      @IBAction func calorieNumberEditingChanged(sender: AnyObject) {
          // If both variables are true and the text fields contain integers, enable button
          if self.yourWeightFilled && self.calorieNumberFilled {
              self.calculateButton.enabled = true
          } else {
              self.calculateButton.enabled = false
          }
      }
      @IBAction func yourWeightEditingChanged(sender: AnyObject) {
          // If both variables are true and the text fields contain integers, enable button
          if self.yourWeightFilled && self.calorieNumberFilled {
               self.calculateButton.enabled = true
          } else {
              self.calculateButton.enabled = false
          }
      }
      

      【讨论】:

      • 非常感谢!这有帮助!也很容易解决(不敢相信我没听懂)!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      相关资源
      最近更新 更多