【问题标题】:Swift Xcode 6: How do I use multiple functions in one statement?Swift Xcode 6:如何在一个语句中使用多个函数?
【发布时间】:2014-11-11 22:23:28
【问题描述】:

我是 xcode 和 swift 的新手,我在使用两个 IBAction 来启用按钮时遇到问题。我有 2 个文本字段,并且我有一个禁用的按钮。我希望在填写两个文本字段时启用按钮。我该怎么做?到目前为止,我已经为两个文本字段声明了两个带有 IBActions 的函数:

 @IBAction func yourWeightEditingDidBegin(sender: AnyObject) {

}

@IBAction func calorieNumberEditingDidBegin(sender: AnyObject) {

}

谢谢!

【问题讨论】:

    标签: xcode function swift uibutton uitextfield


    【解决方案1】:

    一种方法是使用 UITextFieldDelegate 函数而不是 IBOutlets:

    func textFieldShouldReturn(textField: UITextField!) -> Bool {
    
        textField.resignFirstResponder()
    
        if yourWeight.text != ""  && calorieNumber.text != "" {
    
            button.enabled = true
        }
    
        return true
    }
    

    【讨论】:

      【解决方案2】:

      我也实现了UITextFieldDelegate,但我使用shouldChangeCharactersInRange。这样,该按钮的状态会随着用户键入而改变:

      如果只处理两个文本字段,它看起来像:

      func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
      
          // get the value this text field will have after the string is replaced
      
          let value: NSString = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
      
          // get the value of the other text field
      
          let otherValue = textField == yourWeight ? calorieNumber.text : yourWeight.text
      
          // only enable done if these are both non-zero length
      
          doneButton.enabled = (value != "" && otherValue != "")
      
          return true
      }
      

      很明显,要使其工作,您必须为这两个文本字段(在 IB 中或以编程方式)指定 delegate。我通常也将上述内容与文本字段的“自动启用返回键”选项结合起来。

      【讨论】:

      • 这似乎是另一个不错的选择。谢谢!
      【解决方案3】:

      你没有。相反,尝试这样的事情

      var weightIsFilled = false
      var calorieNumberIsFilled = false
      
      @IBAction func yourWeightEditingDidBegin(sender: AnyObject) {
       if valueOfWeightTextFieldIsValid() {
         self.weightIsFilled = true
       }
       if self.weightIsFilled && self.calorieNumberIsFilled {
         self.enableButton()
       }
      }
      
      @IBAction func calorieNumberEditingDidBegin(sender: AnyObject) {
       if valueOfCalorieNumberTextFieldIsValid() {
         self.calorieNumberIsFilled = true
       }
       if self.weightIsFilled && self.calorieNumberIsFilled {
         self.enableButton()
       }
      }
      

      您可能还想使用在文本字段值更改时调用的 IBAction 函数,而不是在开始编辑时调用。

      【讨论】:

      • 这也有更多帮助,因为我只希望文本字段的值是整数。
      • 我知道这要求很多,但我怎么能说文本字段的值只能是整数呢?抱歉,我只是在学习 swift。
      猜你喜欢
      • 1970-01-01
      • 2019-12-20
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多