Home > Software engineering >  In Swift, how can you ensure that only one of two text fields is fillable?
In Swift, how can you ensure that only one of two text fields is fillable?

Time:10-21

Say you have an email field and a cell phone field. If the user fills in the email field, the cell phone field cannot be filled anymore, visa versa.

Here is what I tried below. Making the one field the delegate of the other currently only prevents "Done" from exiting the keyboard, it doesn't make the other text field inactive.

In viewDidLoad

 self.cellField.delegate = emailField as? UITextFieldDelegate

then outside

func textFieldShouldBeginEditing(cellField: UITextField) -> Bool {
    if emailField.text?.isEmpty == false {
    return false
    } else {
        return true
    }
 } //// I also tried textFieldDidBeginEditing

CodePudding user response:

Make both

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 
}  
  • Related