Possible Duplicate:
dismissModalViewController AND pass data back
I'm new to ios development and stuck on this problem:
I'm using storyboarding and have a navigation controller, vcA
, with a TableView
in it which shows some data from a MutableArray
(which is initialized in viewdidload
of the same class). After selecting any cell, a second view controller, vcB
, is shown with a TextField
in it and a button called "Add to list".
What I want is that when I enter some text in the TextField
and press the "Add to list" button the text should be added to the array of previous view (which gets shown in the TableView
) and when i tap the "Back" button on vcB
's navigation bar, vcA
should show the updated TableView
with the new entry in it (on the top of list). Basically I want to add the text from vcB
's TextField
to the array of vcA
and show the new array after clicking the BACK button.
I have searched a lot about this issue and seem to find that delegate and protocols is the way to achieve the desired result but I'm having trouble understanding delegation.
I have the second view controller presenting itself as modal in this example:
In the second view controllers h file:
@protocol SecondViewControllerDelegate <NSObject>
- (void)addItemViewController:(id)controller didFinishEnteringItem:(NSString *)item;
@end
@interface SecondPageViewController : UIViewController <UITextViewDelegate>
{
NSString *previouslyTypedInformation;
}
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (nonatomic) NSString *previouslyTypedInformation;
@property (nonatomic, weak) id <SecondViewControllerDelegate> delegate;
In the second view controllers m file make sure to synthesize properties and add then add this:
- (IBAction)done:(id)sender
{
NSString *itemToPassBack = self.textView.text;
NSLog(@"returning: %@",itemToPassBack);
[self.delegate addItemViewController:self didFinishEnteringItem:itemToPassBack];
//dismiss modal view controller here
}
Then in the first view controllers h file set it as delegate:
@interface FirstPageViewController: UIViewController <SecondViewControllerDelegate>
@property (nonatomic) NSString *returnedItem;
Then in the first view controller's m file synthesize and add the method:
- (void)addItemViewController:(SecondPageViewController *)controller didFinishEnteringItem: (NSString *)item
{
//using delegate method, get data back from second page view controller and set it to property declared in here
NSLog(@"This was returned from secondPageViewController: %@",item);
self.returnedItem=item;
//add item to array here and call reload
}
Now you have the text of what was returned! You can add the string to your array in the first view controller's viewDidLoad and call
[self.tableView reloadData];
and it should work.
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