【问题标题】:Pass data on dismiss to view controller outside of navigation controller?将关闭时的数据传递给导航控制器之外的视图控制器?
【发布时间】:2017-01-19 00:36:18
【问题描述】:

如上图所示,我有两个视图控制器,其中一个在导航控制器中。当在控制器 A 中按下按钮时,控制器 B 通过导航控制器呈现并模态显示。当在 B 上调用解除函数时,我是否可以将数据从控制器 B 传递回控制器 A?

【问题讨论】:

  • Modal segue 应该从 A 指向阅读您的描述的导航控制器

标签: ios swift uinavigationcontroller


【解决方案1】:

您可以使用委托模式或回调来做到这一点

【讨论】:

  • 我已经尝试了这两种方法,但这需要我呈现视图控制器 B,而不是导航控制器。呈现 B 而不是导航控制器不起作用,因为我需要能够呈现和关闭整个视图控制器,而不仅仅是 B。
  • 在这种情况下,最简单的方法是使用unwind segue
  • 而且您仍然可以使用委托,例如在 A:if let navigationController = segue.destination as? UINavigationController, let b = navigationController.viewControllers.first as? BViewController{ b.delegate = self }。并在解除 B 之前使用数据调用委托方法
【解决方案2】:

如果您正在使用情节提要并使用 segue 进行导航,则展开 segue 将为您完成此操作。这是一个应该有所帮助的简单教程:

https://www.andrewcbancroft.com/2015/12/18/working-with-unwind-segues-programmatically-in-swift/

此堆栈溢出答案包含有关此主题的更详细和有价值的信息

Passing Data between View Controllers

【讨论】:

    【解决方案3】:

    你可以通过 NSNotificationCentre 。

    首先您需要在 ViewControllerA 中添加 Notification Observer 及其选择器,如下所示:

    [[NSNotificationCenter defaultCenter] addObserver:self
                                              selector:@selector(receiveTestNotification:) name:@"notificationName"
                                                   object:nil];
    
    -(void) receiveTestNotification:(NSNotification*)notification
    {
      NSDictionary* userInfo = notification.userInfo;
      NSLog (@"%@",userInfo);
    }
    

    现在在 ViewController B 中你需要发布如下通知:

     NSDictionary* userInfo = your data ;
     NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
    [nc postNotificationName:@"notificationName" object:self userInfo:userInfo];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-30
      • 2015-02-10
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      相关资源
      最近更新 更多