在 Swift 中,如何确保两个文本字段中只有一个是可填写的?
In Swift, how can you ensure that only one of two text fields is fillable?
假设您有一个电子邮件字段和一个单元格 phone 字段。如果用户填写了电子邮件字段,单元格 phone 字段将无法再填写,反之亦然。
下面是我试过的。使一个字段成为另一个字段的委托目前只能防止“完成”退出键盘,不会使另一个文本字段处于非活动状态。
在viewDidLoad中
self.cellField.delegate = emailField as? UITextFieldDelegate
然后在外面
func textFieldShouldBeginEditing(cellField: UITextField) -> Bool {
if emailField.text?.isEmpty == false {
return false
} else {
return true
}
} //// I also tried textFieldDidBeginEditing
两者都做
self.cellField.delegate = self
self.emailField.delegate = self
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if textField == cellField {
return emailField.text!.isEmpty
} else if textField == emailField {
return cellField.text!.isEmpty
}
return true
}
假设您有一个电子邮件字段和一个单元格 phone 字段。如果用户填写了电子邮件字段,单元格 phone 字段将无法再填写,反之亦然。
下面是我试过的。使一个字段成为另一个字段的委托目前只能防止“完成”退出键盘,不会使另一个文本字段处于非活动状态。
在viewDidLoad中
self.cellField.delegate = emailField as? UITextFieldDelegate
然后在外面
func textFieldShouldBeginEditing(cellField: UITextField) -> Bool {
if emailField.text?.isEmpty == false {
return false
} else {
return true
}
} //// I also tried textFieldDidBeginEditing
两者都做
self.cellField.delegate = self
self.emailField.delegate = self
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if textField == cellField {
return emailField.text!.isEmpty
} else if textField == emailField {
return cellField.text!.isEmpty
}
return true
}