只要文本字段为空,我就有以下代码来禁用按钮:
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{
addButton.isEnabled = true
} else {
addButton.isEnabled = false
}
return true
}
它工作正常,但现在我有 3 个文本字段,如果所有文本字段都不为空,我只想启用按钮。到目前为止,只要填写了一个文本字段,就会启用该按钮。
我该如何调整我的代码来做到这一点?
最佳答案
将目标添加到 .editingChanged
事件的所有文本字段,并检查是否有任何文本字段为空。如果所有文本字段都包含文本,则启用该按钮,否则禁用该按钮。
class TestViewController: UIViewController, UITextFieldDelegate {
let addButton = UIButton()
let textField1 = UITextField()
let textField2 = UITextField()
let textField3 = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
textField1.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
textField2.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
textField3.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
}
@objc func textChanged(_ textField: UITextField) {
addButton.isEnabled = [textField1, textField2, textField3].contains { $0.text!.isEmpty }
}
}
关于ios - 只要几个文本字段为空,就禁用按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56166818/