I have multiple buttons in ViewA. When a button is clicked, it is redirected to ViewB. In ViewB, the user does some interactions, and then clicks the back button when he is done. How do I run a method and pass in a parameter from ViewB into ViewA and then continue working in ViewA?
Using the back button is strongly required, but I am keen to learn if there are other ways.
My idea was to get the ViewA from the stack, and when I am done with ViewB, just call upon it and redirect, but I couldn't figure out how to do it.
Thank you.
You want to define a delegate in ViewB and implement it in ViewA. At the appropriate time (e.g., when the back button is tapped) ViewB call the delegate method, passing the value as a parameter.
Something like this:
ViewB.h
// Define a delegate protocol allowing
@protocol ViewBDelegate
// Method of delegate called when user taps the 'back' button
-(void) backButtonSelected:(id) object;
@end
@interface ViewB : UIViewController
// property to hold a reference to the delegate
@property (weak)id<ViewBDelegate> delegate;
-(IBAction)backButtonSelected:(id)sender;
@end
ViewB.m:
@implementation ViewB
...
-(IBAction)backButtonSelected:(id)sender{
NSObject *someObjectOrValue = nil;
// Invoke the delegates backButtonSelected method,
// passing the value/object of interest
[self.delegate backButtonSelected:someObjectOrValue];
}
@end
ViewA.h:
#import "ViewB.h"
// The identifier in pointy brackets (e.g., <>) defines the protocol(s)
// ViewA implements
@interface ViewA : UIViewController <ViewBDelegate>
...
-(IBAction)someButtonSelected:(id)sender;
@end
ViewA.m:
-(IBAction) someButtonSelected:id @implementation ViewA
...
// Called when user taps some button on ViewA (assumes it is "hooked up"
// in the storyboard or IB
-(IBAction)someButtonSelected:(id)sender{
// Create/get reference to ViewB. May be an alloc/init, getting from storyboard, etc.
ViewB *viewB = // ViewB initialization code
// Set `ViewB`'s delegate property to this instance of `ViewA`
viewB.delegate = self;
...
}
// The delegate method (defined in ViewB.h) this class implements
-(void)backButtonSelected:(id)object{
// Use the object pass as appropriate
}
@end
In iOS6 you can now use Unwind Segues. In Storyboard you might have noticed the new Exit buttons that can be used for this.
Unwind Segues will allow you to transition back from viewControllerB to viewControllerA and to provide info back through the prepareForSegue method.
Currently documentation is rather limited, but there is a useful WWDC2012 video on how to do this (Session 236)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With