【问题标题】:Passing parameter when pop view弹出视图时传递参数
【发布时间】:2014-06-21 01:40:12
【问题描述】:

我正在构建一个 ios 应用程序,其中有两个视图 A 和 B 之间的导航。

导航模式是:

ViewController A >>> PushViewController >>> ViewController B

ViewController A <<< PopViewController <<< ViewController B

我希望当B 弹回到A 时,A 会相应地更新一些 UI 元素。例如,A 视图控制器显示一些带有文本的标签,在 B 用户修改文本,当视图弹出时,我希望 A 更新并反映更改。

问题是:A 如何知道它何时从B 弹出?以及A 如何获取B 传递的数据以便更新内容?解决此类问题的最佳做法是什么?

谢谢

【问题讨论】:

  • 你有没有想过为你的控制器实现一个委托协议?
  • 您可以使用 nsnotification center 或将主视图控制器嵌入到导航控制器上,并使用故事板设置 segue 并使用 prepareForSegue 调度它并使用 push 传递值
  • 再次阅读您的问题,您需要一个导航控制器。并且要将值从 a 传递到 b,您需要将您认为 b 期望的值推送到您将视图 controller.h b 导入到 view controller.m 上,并且必须知道您传递给 b 的值必须在 a 上定义。稍后使用情节提要链接 a 和 b 与 push segue。告诉我是否有帮助
  • 委托是迄今为止您可以采用的最简单且最不容易出错的方法。在简单的一对一关系中,我会远离通知。
  • 我认为只使用属性引用,和 UIViewController 生命周期方法就可以解决问题,只需在两个控制器中创建一个属性,从A-&gt;B 传递,在B 上分配值和POP, A 将具有该值,因为它具有相同的引用。在viewWillAppear 或viewDidAppear 上更新A 中的值。

标签: ios objective-c uiview uiviewcontroller


【解决方案1】:

您可以使用NSNotificationCenter 轻松做到这一点:

第一个视图控制器:

// Assuming your label is set up in IB, otherwise initialize in viewDidLoad
@property (nonatomic, strong) IBOutlet UILabel *label;

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Add an observer so we can receive notifications from our other view controller
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateLabel:) name:@"UpdateLabel" object:nil];
}

- (void)updateLabel:(NSNotification*)notification
{
    // Update the UILabel's text to that of the notification object posted from the other view controller
    self.label.text = notification.object;
}

- (void)dealloc
{ 
    // Clean up; make sure to add this
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

第二个视图控制器:

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

    NSString *updateLabelString = @"Your Text Here";        
    // Posting the notification back to our sending view controller with the updateLabelString being the posted object
    [[NSNotificationCenter defaultCenter]postNotificationName:@"UpdateLabel" object:updateLabelString;
}

【讨论】:

  • 实施成功。弹出视图控制器时传递值的简单方法。
【解决方案2】:

您可以在使用PopViewController 时使用委托将对象传递给父视图控制器

逐步使用委托click here进行演示。

这个问题是为了你的帮助Question and answer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    相关资源
    最近更新 更多