在我使用 segues 的项目中,我是这样做的(请注意,我是 iOS 新手,所以可能有“更好”的方法,这对于 iOS 的老手来说可能很明显):
简短版本:在模态视图控制器的.h
文件中定义回调协议。当您的模态视图控制器关闭时,它会检查演示者是否实现了该协议并调用这些方法来传递数据。
所以就像你说的,假设你的模态视图控制器只是从用户那里收集一个字符串值,然后他们点击确定或取消。该类可能如下所示:
@interface MyModalViewController : UIViewController
...
@end
我建议您将这样的协议添加到同一个标头中:
@protocol MyModalViewControllerCallback
-(void) userCancelledMyModalViewController:(MyModalViewController*)vc;
-(void) userAcceptedMyModalViewController:(MyModalViewController*)vc
withInput:(NSString*)s;
@end
然后在 中MyModalViewController.m
,添加viewDidDisappear
类似这样的代码:
-(void) viewDidDisappear:(BOOL)animated {
UIViewController* presenter = self.presentingViewController;
// If the presenter is a UINavigationController then we assume that we're
// notifying whichever UIViewController is on the top of the stack.
if ([presenter isKindOfClass:[UINavigationController class]]) {
presenter = [(UINavigationController*)presenter topViewController];
}
if ([presenter conformsToProtocol:@protocol(MyModalViewControllerCallback)]) {
// Assumes the presence of an "accepted" ivar that knows whether they
// accepted or cancelled, and a "data" ivar that has the data that the
// user entered.
if (accepted) {
[presenter userAcceptedMyModalViewController:self withInput:data];
}
else {
[presenter userCancelledMyModalViewController:self];
}
}
[super viewDidDisappear:animated];
}
最后在父视图中,您实现新的@protocol
,例如.h
:
@interface MyParentViewController : UIViewController <MyModalViewControllerCallback>
...
@end
并在.m
:
@implementation MyParentViewController
...
-(void) userCancelledMyModalViewController:(MyModalViewController*)vc {
// Update the text field with something like "They clicked cancel!"
}
-(void) userAcceptedMyModalViewController:(MyModalViewController*)vc
withInput:(NSString*)s {
// Update the text field with the value in s
}
...
@end