NSNotification 或 Delegate 在可见视图更改时注册

Posted

技术标签:

【中文标题】NSNotification 或 Delegate 在可见视图更改时注册【英文标题】:NSNotification or Delegate to register for when the visible view changes 【发布时间】:2012-10-31 18:36:58 【问题描述】:

我正在为ios 开发一个objective-c 项目,并且我有一个使用UITabBarController 子类的带有多个选项卡的视图。每个选项卡都有自己的 UINavigationController。当视图加载到选项卡上时,会触发相应的激活事件(viewWillAppear、viewDidLoad 等)。但是,一旦您点击不同的选项卡并返回,并非所有这些事件都会再次触发,因为该视图已经是该特定选项卡的可见视图(例如 viewDidLoad)。

我的问题是:是否有一个通知或委托,我可以简单地注册并在窗口中的可见视图发生变化时得到通知?我做了一些研究,但没有找到任何具体的东西。我打算做的是:

    标签栏索引变化时查看可见视图:tabBarController:didSelectViewController 在每个导航控制器上注册此事件:navigationController:didShowViewController:animated:

通过这样做,只要通过更改选项卡或在选项卡的导航流中导航来更改 visibleViewController 时,我都会收到通知(模式除外,在这种情况下,我不关心它们。它们已经被处理了) .

这是正确的方法吗?

【问题讨论】:

【参考方案1】:

你看过 UITabBarControllerDelegate 吗?这种方法听起来你在找什么:

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController

来自文档:

In iOS v3.0 and later, the tab bar controller calls this method regardless 
of whether the selected view controller changed. In addition, it is called only
in response to user taps in the tab bar and is not called when your code 
changes the tab bar contents programmatically.

这是链接:http://developer.apple.com/library/ios/#documentation/uikit/reference/UITabBarControllerDelegate_Protocol/Reference/Reference.html

希望有帮助!

【讨论】:

【参考方案2】:

首先实现UITabBarController委托方法“tabBarController:didSelectViewController”并在应用委托中注册。您不能在每个导航控制器中注册它。只有一个对象可以是委托。在该方法中,将其类型转换为 UINavigationController。

然后通过在 UINavigationController 上调用“topViewController”来获取 UIViewController。然后直接调用viewWillAppear:方法就可以了。

【讨论】:

谢谢。我很快就会试一试——我还有其他一些缺陷需要排除。 :)

以上是关于NSNotification 或 Delegate 在可见视图更改时注册的主要内容,如果未能解决你的问题,请参考以下文章

04 KVC|KVO|Delegate|NSNotification区别

NSNotification\KVO\block\delegate的区别和用法

NSNotification是同步还是异步?和delegate相比有啥区别,效率呢?

(七十二)自己定义通知NSNotification实现消息传递

ios常见的页面传值方式

NSNotification消息