viewWillAppear: not being called inside a UINavigationController

本文介绍了一个关于 UINavigationController 作为 UIViewController 子视图时出现的数据不刷新问题。作者通过调整视图层级并进行重构后发现,在导航控制器中切换视图时未能正确调用 viewWillAppear 方法,导致视图未能更新。文中提供了如何手动调用该方法以解决问题的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

点击打开链接

 

I just stumbled on a small problem that gave me a great headache. I changed the view hierarchy to implement flipping preferences on the back of my App’s main view. Accordingly, I had to move some stuff out of the nibs and into the code. Iin other words, some heavy refactoring, and without testing (I know, bad bad me).

So basically I now have a root UIViewController which has a UINavigationController as a subview; this, in turn, loads a number of UIViewControllers to navigate my items hierarchy.

Today, while working on cosmestic/usability improvements, I realised that something was definitely not working. When moving back and forth in my items, data were not refreshed. This pointed to one culprit, viewWillAppear not being called in the UIViewControllers.

After some googling I found out that if you add a UINavigationController as a subview of a UIViewController subclass, you must explicitly call its viewWillAppear method from its container; otherwise, they won’t be called, and when moving back and forth in the navigation tree, your UIViewControllers’ viewWillAppear: methods won’t be called.

It’s quite simple; assuming that projectNavigationController is a navigation controller added as a a subview of this UIViewController subclass, just make sure you add this simple call:

-(void)viewWillAppear:(BOOL)animated { 
	[super viewWillAppear:animated];
	[projectNavigationController viewWillAppear:animated];
}

 

Of course the same applies to your other viewWill/Did methods

 

-(void)viewWillDisappear:(BOOL)animated { 
	[super viewWillDisappear:animated];
	[projectNavigationController viewWillDisappear:animated];
}
-(void)viewDidAppear:(BOOL)animated { 
	[super viewDidAppear:animated];
	[projectNavigationController viewDidAppear:animated];
}
-(void)viewDidDisappear:(BOOL)animated { 
	[super viewDidDisappear:animated];
	[projectNavigationController viewDidDisappear:animated];
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值