[英]How to access the parent view controller?
I am using this code to push a view controller in ViewControllerA
: 我正在使用此代码在ViewControllerA
推送视图控制器:
DatePickerViewController *viewController = [[DatePickerViewController alloc] initWithNibName:@"DatePickerViewController" bundle:nil];
NSMutableArray *info = [[NSMutableArray alloc] initWithObjects:@"Exam Duration",nil];
[viewController setInfo:info];
[info release];
[self.navigationController pushViewController:viewController animated:YES];
[viewController release];
In the DatePickerViewController
that is slid in, it has a text field. 在滑入的DatePickerViewController
中,它具有一个文本字段。 In ViewControllerA
how can I get the value of this text field once the viewWillDisappear
method is fired, it's to save data. 在ViewControllerA
,一旦触发viewWillDisappear
方法,该如何保存此文本字段的值,即保存数据。
There are several ways to do this. 有几种方法可以做到这一点。 Best would be to use a delegate pattern or a notification system. 最好是使用委托模式或通知系统。
Which one you choose depends on your whishes. 您选择哪种取决于您的意愿。 If you just want the 'parent controller' to know about the value, use a delegate method. 如果只希望“父控制器”知道该值,请使用委托方法。
Using delegates or notifications creates a loosely coupled structure and makes reusable classes possible. 使用委托或通知会创建松散耦合的结构,并使可重用的类成为可能。
EDIT: Some sample code. 编辑:一些示例代码。 Beware: untested and from the top of my head! 当心:未经测试,从我的头顶上!
DatePickerViewController.h DatePickerViewController.h
@protocol DatePickerViewControllerDelegate
-(void)datePicker:(DatePickerViewController *)picker pickedDate:(NSDate *)date;
@end
DatePickerViewController.m DatePickerViewController.m
- (void)viewWillDisappear:(BOOL)animated {
[self.delegate datePicker:self pickedDate:theDate]; //Delegate is an ivar
[super viewWillDisappear:animated];
}
ViewControllerA.m ViewControllerA.m
//
DatePickerViewController *viewController = [[DatePickerViewController alloc] initWithNibName:@"DatePickerViewController" bundle:nil];
NSMutableArray *info = [[NSMutableArray alloc] initWithObjects:@"Exam Duration",nil];
[viewController setInfo:info];
[info release];
[viewController setDelegate:self]; // Set the delegate of the date picker
[self.navigationController pushViewController:viewController animated:YES];
[viewController release];
//
-(void)datePicker:(DatePickerViewController *)picker pickedDate:(NSDate *)date; {
//Deal with the new date here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.