Alessio Crestani
Alessio Crestani

Reputation: 1612

How to know when textfield are changed without saving

there is some design pattern or best practices to implement the "exit without saving changes" in a form? In my Android app i've used a boolean isChanged set to false on initialization of the view, then if the user focus a textfield and change the text, i compare the new text with the old one and if the doesn't match i put the boolean to true. On the pressure of "close" button, i check the boolean and if it's true the app asks to user if they wanna really close the view.

Upvotes: 0

Views: 86

Answers (3)

Tej Patel
Tej Patel

Reputation: 119

Try this: UITextFieldDelegate

//MARK: - UITextfield Delegate Method -
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
    textField.resignFirstResponder()

    if textField.text == ""
    {
        AppDelegate.sharedInstance().showAlertAction(strTitle: "OK", strMessage: "Please enter keyword for search.")
        { (success) in

        }
    }
    else
    {
        let searchVC = self.storyboard?.instantiateViewController(withIdentifier: "SearchViewController") as! SearchViewController
        searchVC.strSearchVal = SAFESTRING(str: self.txtSearch.text!)
        searchVC.isFromHome = true
        self.navigationController?.pushViewController(searchVC, animated: true)
    }
    return true
}

Upvotes: 0

Gyanendra Singh
Gyanendra Singh

Reputation: 1483

You can use the UITextfield Delegate methods in your viewController class.

When user tap on the text field this method gets called

- (void)textFieldDidBeginEditing:(UITextField *)textField{
  //Set the boolean false here.
 }

While user is typing this method gets called.

- (BOOL)textField:(UITextField *)textField 
        shouldChangeCharactersInRange:(NSRange)range 
        replacementString:(NSString *)string{
}

When user stop typing and keyboard returns then this methods gets called.

- (void)textFieldDidEndEditing:(UITextField *)textField{
 // Set the boolean true here
}

if boolean is true then compare the current value to old value and decide the flow.

 if(boolean){
    NSString *currentString = textfield.text;
    if([previousString isEqualToString:currentString])
      NSLog("not edited");
} 

Upvotes: 1

larva
larva

Reputation: 5148

Try use TextfieldDelegate function - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField

Upvotes: 0

Related Questions