Search code examples
swiftuitextfielduser-interaction

How to change textField user-interaction according to condition in Swift


I have two textfields called toDateTextField and fromDateTextField

my need is if fromDateTextField.text?.isEmpty ?? true then if i tap on toDateTextField then it has to show toast and should not open datepicker

with this code if i tap initially on toDateTextField then datepicker is not opening but it is not showing toast.. how to show toast initially if i tap on toDateTextField

and if i initially tap on fromDateTextField then its showing toast message and then datepicker is coming.. how to solve this two issues

override func viewDidLoad() {
super.viewDidLoad()

toDateTextField.isEnabled = false
}


func textFieldDidBeginEditing(_ textField: UITextField) {

if fromDateTextField.text?.isEmpty ?? true {


       toDateTextField.isEnabled = false
    self.view.makeToast("Please select from date")


    } else {
       toDateTextField.isEnabled = true
}
}

//this is datpicker done button 
@objc func doneButtonPressed(_ sender: UIBarButtonItem) {

toDateTextField.isEnabled = true

let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let arr = [fromDateTextField,toDateTextField]
    let current = arr[sender.tag]
    if let datePicker = current?.inputView as? UIDatePicker {
        current?.text = dateFormatter.string(from: datePicker.date)
        current?.resignFirstResponder()
    }

}

how to solve this two issues.. please do help


Solution

  • Nothing will happen if you initially tap on toDateTextField because you have set its enabled property to false in viewDidLoad method.

    And you will get the toast message as soon as you start modifying fromDateTextField because it is empty at the beginning.

    To solve that, you need to do some modifications in textFieldDidBeginEditing so that it detects which textField is currently being changed and do what you want accordingly.

    func textFieldDidBeginEditing(_ textField: UITextField) {
        
        if textField == toDateTextField {
            if fromDateTextField.text?.isEmpty ?? true {
                self.view.makeToast("Please select from date")
                toDateTextField.isEnabled = false
            }
        }
    }
    

    And to enable toDateTextField you need to add the following:

    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField == fromDateTextField {
                toDateTextField.isEnabled = true
        }
    }
    

    Note: You need to set delegate of both textFields to self in your viewDidLoad for this solution to work properly.