UIViewController parentViewController access properties

Dave picture Dave · Mar 9, 2010 · Viewed 14.6k times · Source

I know this question has been asked several times and I did read existing posts on this topic but I still need help.

I have 2 UIViewControllers - parent and child. I display the child UIViewController using the presentModalViewController as below:

ChildController *child = 
 [[ChildController alloc] initWithNibName:@"ChildView" bundle:nil];
[self presentModalViewController:child animated:YES];
[child release];

The child view has a UIPickerView. When user selects an item from UIPickerView and clicks done, I have to dismiss the modal view and display the selected item on a UITextField in the parent view.

In child's button click delegate, I do the following:

ParentController *parent = 
 (ParentController *)[self.navigationController parentViewController];
[parent.myTextField setText:selectedText];
[self dismissModalViewControllerAnimated:YES];

Everything works without errors. But I don't know how to load the parent view so that it displays the updated UITextField.

I tried

[parent reloadInputViews];

doesn' work. Please help.

Answer

Dave picture Dave · Mar 17, 2010

Delegation is the way to go. I know some people that may be looking for an easier solution but trust me I have tried others and nothing works better than delegation. So anyone having the same problem, go read up on delegation and follow it step by step.

In your subviewcontroller.h - declare a protocol and declare delegate mthods in it.

@protocol myDelegate
 -(void)clickedButton:(subviewcontroller *)subController;
@end

In your subviewcontroller.h, within @interface:

id<myDelegate> delegate;
@property (nonatomic, assign) id<myDelegate> delegate;    
NSString *data;
-(NSString *)getData;

In your subviewcontroller.m, synthesize myDelegate. Add the following code to where you want to notify your parentviewcontroller that the subview is done doing whatever it is supposed to do:

 [delegate clickedButton:self];

and then handle getData to return whatever data you want to send to your parentviewcontroller

In your parentviewcontroller.h, import subviewcontroller.h and use it's delegate

 #import "subviewcontroller.h"
 @interface parentviewcontroller : VUIViewController <myDelegate>
 {}

In your parentviewcontroller.m, implement the delegate method

 - (void)clickedButton:(subviewcontroller *)subcontroller
 {
   NSString *myData = [subcontroller getData];
   [self dimissModalViewControllerAnimated:YES];
   [self reloadInputViews];
 }

Don't forget memory management!