Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone: Save with validation on back navigation

In my iPhone application I have navigation controller, main screen and some edit screens. On edit screen user does some input that has to be validated before I can save it. Ideally I would like to update data automatically on back navigation without additional "Done" button. Can I do some validation and save on back navigation (i.e. when user taps on standard back button) in a way that allows my to stop navigation and show some error message if something is wrong?

I see several other possibilities:

  • Create my custom left button and make it looks like standard back. (Why Apple didn't put this button style into public API?)
  • Add "Done" button and save data only if user taps it

but both these choices I like much less. So if there is a way to achieve what I want, I'd like to use it.

like image 885
SergGr Avatar asked Mar 08 '26 00:03

SergGr


1 Answers

Basically you want to override the action from the backBarButton of your root view controller and do your validation there. If validation passes call the UINavigationController popViewControllerAnimated:, otherwise show an error alert or whatever.

However, if you try to set the target and action properties for the root view controllers navigationItem.backBarButton it won't work. Apparently these have to be nil.

A way round this maybe to replace the standard back bar button with a custom button. You could do that with a standard UIBarButtonItem, but you would lose the 'arrow' shape since this is not available as one of the styles. A workaround for that maybe to use a custom view for the button. Check out this thread for an example of doing that.

like image 130
cidered Avatar answered Mar 10 '26 14:03

cidered



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!