【问题标题】:how to check textfield is not empty and button enable如何检查文本字段不为空和按钮启用
【发布时间】:2021-11-12 08:29:38
【问题描述】:

我想检查文本字段是否为空

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        if !text.isEmpty {
            self.completeRegisterBtn.isEnabled = true
        } else {
            self.completeRegisterBtn.isEnabled = false
        }
        
        return true
    }

这是我的代码,但它只是检查输入的新文本。 我已经按数据输入了文本字段。 怎么查?

此外,不仅要检查文本字段,还要选择一个按钮(来自 2 个按钮)检查

请帮助我。谢谢

【问题讨论】:

  • 设置数据后,您需要调用一个检查所有字段并设置按钮状态的函数
  • 我的函数无法调用。是代表。但是非常感谢!我可以找到另一种方式
  • 您可以检查 textField.text.isEmpty ,然后您可以执行相同的按钮启用或禁用。

标签: ios swift xcode


【解决方案1】:

我附上了如何检查 textFiled 是否为空的代码

let txtField = UITextField()
txtField.text = "testing"
if txtField.text != "" {
    btn_Pause.isEnabled = true
} else {
    btn_Pause.isEnabled = false
}

-> 使用 isEmpty 函数

if txtField.text?.isEmpty == true {
    btn_Pause.isEnabled = false
} else {
    btn_Pause.isEnabled = true
}

-> 使用字符数

if txtField.text?.count ?? 0 > 0 {
    btn_Pause.isEnabled = true
} else {
    btn_Pause.isEnabled = false
}

【讨论】:

  • 我想检查两个按钮被选中并且文本字段不为空
【解决方案2】:

根据您的评论回答:

if textField.text != "" && btn.isSelected {
            
 }

【讨论】:

    【解决方案3】:

    只要做这样的函数,然后在你想使用的地方调用它

    func dataValidation(text: String) {
    
      btn.isEnable = (text.isEmpty ?? false) ? false : true 
    
    }
    

    使用方法:

    dataValidation(text: "test") 
    

    【讨论】:

      【解决方案4】:

      试试这个

      if let text = textfield.text, !text.isEmpty {
          completeRegisterBtn.isEnabled = true
      } else {
          completeRegisterBtn.isEnabled = false
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-28
        • 1970-01-01
        相关资源
        最近更新 更多