Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - How to make a backBarButtonItem also execute a custom function?

I am an iOS development newbie. I am using the following code to set my backBarButtonItem -

UIBarButtonItem *temporaryBarButtonItem=[[UIBarButtonItem alloc] init];
temporaryBarButtonItem.title=@"Back";
self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
[temporaryBarButtonItem release];

I also want it to execute another function, apart from going back. Is that possible? Or do I need another button to save?

like image 649
Suchi Avatar asked Dec 09 '22 05:12

Suchi


1 Answers

You can practically do that in your viewDidDisappear or viewWillDisappear method.

If this view can only go back and doesn't present any views, then this should work.

However, if you plan on presenting a subview, modal view, go deeper in the navigation hierarchy, or do other view operations that will cause viewDidDisapper to get called, then you'll need to separate your back-button code logic somehow.

For instance if you will present a modal view from this view, you can check if self.modalViewController is nil, if it is then you have no modal view being present and can safely execute the back-button code. If it is not nil then you have a modal view present and should not execute back-button code. (viewWillDisappear should register the modal view controller as not-nil).

like image 167
JoePasq Avatar answered May 30 '23 13:05

JoePasq