【问题标题】:How to pass an NSString from modal view to parent view如何将 NSString 从模态视图传递到父视图
【发布时间】:2012-06-10 15:13:30
【问题描述】:

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

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

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

【问题讨论】:

    标签: nsstring modalviewcontroller segue parentviewcontroller


    【解决方案1】:

    在我使用 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
    

    【讨论】:

    • 你在这里的做法对我来说有点道理。但是,我无法弄清楚如何让我的代码为我工作而不会出错。你有任何示例代码,以便我可以偶然看到它的工作原理吗?
    猜你喜欢
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    相关资源
    最近更新 更多