ios - 弹出 View 时传递参数

标签 ios objective-c uiview uiviewcontroller

我正在构建一个 ios 应用程序,其中有两个 View AB 之间的导航。

导航模式是:

ViewController A >>> PushViewController >>> ViewController B

ViewController A <<< PopViewController <<< ViewController B

我希望当 B 返回到 A 时,A 相应地更新一些 UI 元素。例如,A View Controller 显示一些带有文本的标签,在 B 用户修改文本,当 View 弹出时,我希望 A 到更新并反射(reflect)更改。

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

谢谢

最佳答案

您可以使用 NSNotificationCenter 轻松完成此操作:

第一个 View Controller :

// 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];
}

第二 View Controller :

- (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;
}

关于ios - 弹出 View 时传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24337521/

相关文章:

ios - 一个应用 "intercept"在iOS中的openURL方法怎么办?

iOS - 在 View Controller 中绘制一个 donut

objective-c - 如何使用 GCC 编译 Objective-C 代码?

ios - 如何在 ViewController 中将 AVPlayer 添加到 UIView

ios - 更改 timeAgo 使系统过期

ios - 子类化自定义 UIViewController(使用 xib)以添加其他行为

objective-c - NSWorkspace选择文件:inFileViewerRootedAtPath: does not work the first time it is called

ios - 如何在单击 tableviewcell 中的按钮时更新 UIView

ios - 如何在单击时从一个 ViewController(包含自定义 UIView)移动到另一个 ViewController(包含 UITableView)?

Ios 本地化不起作用