All*_*ang 2 objective-c uiviewcontroller uiview ios
我正在构建一个ios应用程序,其中有两个视图之间的导航A和B.
导航模式是:
ViewController A >>> PushViewController >>> ViewController B
ViewController A <<< PopViewController <<< ViewController B
Run Code Online (Sandbox Code Playgroud)
我希望当B弹出时A,A会相应地更新一些UI元素.例如,A视图控制器显示一些带有文本的标签,在B用户中修改文本,当视图弹出时,我想A更新并反映更改.
问题是:怎么A知道它什么时候开始B?如何A获取数据,B以便更新内容?解决这类问题的好方法是什么?
谢谢
您可以通过以下方式轻松完成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];
}
Run Code Online (Sandbox Code Playgroud)
第二视图控制器:
- (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;
}
Run Code Online (Sandbox Code Playgroud)