I recently came across a problem using the newest version of XCode (4.4), in which we can use the fantastic Storyboards feature. The question was simple – how do I present a modal view, ask the user for some data, and then return that to the parent view? In the past it was a pretty simple matter, but for me passing it back along via a navigation controller turned out to be slightly more complex that I predicted. Luckily the code to fix this issue is pretty concise and very easy to understand. Let’s take a look.
Here’s what we’re dealing with in terms of the view setup:
First thing’s first, give your modal segue an identifier like so:
Make this descriptive, for my app the modal view is used to add an order. And now we need to get our hands dirty and start coding. Jump to the modal view’s header file and add this property:
@property (nonatomic, assign) id delegate;
This will allow us to assign a delegate to our view, in our case will allow the parent view to tell the modal view that it is the delegate, and therefore all data should be passed back to our parent. Note: Don’t forget to @synthesize
the above property in your .m
file.
Now let’s imagine you want to pass back the contents of an input box when a button is tapped, I’ll assume you’ve setup a method called didFinishEnteringData:sender
– a fairly common looking method name as generated by XCode. Here’s the code you would use inside of this method:
- (IBAction)didFinishEnteringData:(id)sender { [self.delegate setInput:myInput.text]; [self dismissModalViewControllerAnimated:YES]; }
And voilà! We are now talking to our delegate. But hang on, we need to have our parent assign itself as the delegate before the modal view is presented. And for that we need to jump to our parent view – an excellent point here is that the method applies to the storyboard configured method of presenting a modal view, rather than a programmatic approach. Here’s the code:
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if([segue.identifier isEqualToString:@"NewOrder"]){ AddOrdersViewController *vc = (AddOrdersViewController *)[[[segue destinationViewController] viewControllers] objectAtIndex:0]; [vc setDelegate:self]; } }
Notice the use of the identifier we configured before. Also note the modal view’s class name, and the need to #import
the header file of the modal view’s class.
And that is how to simply access the parent to send data back from a modal view!
Comments
One response to “Pass data from modal view back to parent in the iOS SDK”
I was trying to do exactly this, but with a tableview with selections.However my Xcode is giving out about the setInput part. Obviously I have it wrapped up in the DidSelect…
Jorgen