Storing UITextField contents before view pops

痴心易碎 提交于 2019-11-30 18:20:35

OK, I figured out a simple solution after a lot of web-surfing, forum reading, and manual reading. It was, as I suspected, very simple, only one line of code added. In the viewWillDisappear method of the EditViewContorller I simply added:

    [self.view.window endEditing: YES];

Now textFieldShouldEndEditing, textFieldEditingEnded, and textFieldDidEndEditing all get fired off before the viewWillAppear of the master view does.

So now the viewWillDisappear method looks like:

- (void) viewWillDisappear: (BOOL) animated {
    [super viewWillDisappear: animated];
    NSLog( @"In viewWillDisappear" );
    // Force any text fields that might be being edited to end so the text is stored
    [self.view.window endEditing: YES];
}

And the methods already in place to handle the 'Return' on the keyboard also handle the 'Back' button on the Navigation controller.

Thank you Aaron and Jeff for your assistance and helping me think this through.

Why not just create your own Back button with that logic in its action method?

I would think that from a UX perspective, you should display an alert to determine if the user wants to cancel the edit action they were in the middle of before exiting the current view.

By alerting the user, you can see if they hit the button by accident or if they did decide to leave the view, take the appropriate action.

// add this to the field(s) to be edited, selector will be called as the changes
// are being made... still difficult to handle a cancel, but should work
[objectToEdit addTarget:self action:@selector(updateNameField:) 
                         forControlEvents:UIControlEventEditingChanged];

additional code here...

// the method called to update object from parent view
- (void)updateNameField:(id)sender {
    <OBJECT TO UPDATE>.text = ((UITextField *)sender).text;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!