如何访问父视图控制器? [英] How to access the parent view controller?

查看:59
本文介绍了如何访问父视图控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码在 ViewControllerA 中推送视图控制器:

I am using this code to push a view controller in 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];

DatePickerViewController 中,它有一个文本字段。在 ViewControllerA 中,一旦触发 viewWillDisappear 方法,如何获取此文本字段的值,这是为了保存数据。

In the DatePickerViewController that is slid in, it has a text field. In ViewControllerA how can I get the value of this text field once the viewWillDisappear method is fired, it's to save data.

推荐答案

有几种方法可以做到这一点。最好是使用委托模式或通知系统。

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.

编辑:一些示例代码。当心:未经测试,从我的头顶上!

DatePickerViewController.h

@protocol DatePickerViewControllerDelegate
    -(void)datePicker:(DatePickerViewController *)picker pickedDate:(NSDate *)date;
@end

DatePickerViewController.m

- (void)viewWillDisappear:(BOOL)animated {
    [self.delegate datePicker:self pickedDate:theDate]; //Delegate is an ivar
    [super viewWillDisappear:animated];
}

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
}

这篇关于如何访问父视图控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆