iphone开发之解决viewWillAppear失效

本文探讨了在iOS应用开发中使用UINavigationController时,导致viewWillAppear方法未被调用的原因及解决方法,提供了两种实用的解决方案,并强调了在特定场景下正确设置UINavigationControllerDelegate的重要性。

你可曾遇到过viewWillAppear没有被调用到的情况

产生原因是用了UINavigationController.
将UINavigationController的view作为subview添加到了其他viewController的view中。
或者把UINavigationController添加到UITabbarController中了。

此时,NavigationController的stack里面的viewController就收不到-(void)viewWillAppear:(BOOL)animated;等4个方法的调用。

原因呢

Apple Docs state:

Warning: If the view belonging to a view controller is added to a view hierarchy directly, the view controller will not receive this message. If you insert or add a view to the view hierarchy, and it has a view controller, you should send the associated view controller this message directly. Failing to send the view controller this message will prevent any associated animation from being displayed.

不过后面的到4.0的文档就没有发现这样的文字描述了,但是还是没能够调用的到这样

只是添加的更复杂的文档,头晕晕看不下去了。

解决方法两种:
1,在导航控制器上层controller的viewWillAppear中显式调用viewWillAppear方法。

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

- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[subNavCntlr viewWillDisappear:animated];
}

2,把导航控制器上层controller设为UINavigationController的delegate

nav.delegate = self;

@interface 
RootViewController : UIViewController <UINavigationControllerDelegate> {
    UINavigationController *navController;
}

- (void
)navigationController:(UINavigationController *)navigationController 
    willShowViewController:(UIViewController *)viewController animated:(BOOL
)animated 
{
    [viewController viewWillAppear:animated];
}

- (void
)navigationController:(UINavigationController *)navigationController 
    didShowViewController:(UIViewController *)viewController animated:(BOOL
)animated 
{
    [viewController viewDidAppear:animated];
}

凑合着用吧,我喜欢第二种,不过我更喜欢干脆不再viewWillappear里做事情了。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值