0

我有一个父视图和一个带有文本框的模式视图。我想要做的是将模式视图中输入的任何内容传递到文本框中,然后将其传递给父视图中的标签,该标签将标签更新为输入的内容。我希望这有任何意义。

几个星期以来,我一直在拔头发,试图解决这个问题,但没有运气。我发现了许多关于 segues 和在被推送的视图之间传递的示例和教程,但没有关于模态视图和传递回父视图的内容。

我一直试图理解这一点,需要一个很好的例子。我有点理解为 segue 做准备的概念,但由于某种原因,我无法弄清楚这一点。对此的任何帮助将不胜感激,您将成为我一生的英雄,哈哈。

4

1 回答 1

0

在我使用 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
于 2012-06-06T15:56:11.223 回答