我正在构建一个ios应用,其中两个视图A
和B
之间有导航。
导航模式是:
ViewController A >>> PushViewController >>> ViewController B
ViewController A <<< PopViewController <<< ViewController B
我希望当B
弹出回A
时,A会相应地更新一些UI元素。例如,A
视图控制器会显示一些带文字的标签,在B
用户修改文字,当视图弹回时,我希望A
更新并反映更改。
问题是:A
如何知道它来自B
的时间?以及A
如何通过B
传递数据以便更新内容?解决这类问题的好方法是什么?
谢谢
答案 0 :(得分:6)
您可以使用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;
}
答案 1 :(得分:2)