我希望在导航栏中有一个自定义计时器对象,用于显示时间并响应消息(start
,stop
等)。我已使用以下代码(放在UIViewController的viewDidLoad
中)成功将子视图控制器添加到我的UINavigationBar中:
self.timerViewController=[[TimerViewController alloc] init];
self.timerViewController.delegate=self;
[self.timerViewController.view setFrame:CGRectMake(935,
-20,
self.timerViewController.view.frame.size.width,
self.timerViewController.view.frame.size.height)];
[self.navigationController addChildViewController:self.timerViewController];
[self.navigationController.navigationBar addSubview:self.timerViewController.view];
我的问题是这种方法是否有问题?例如,有一个navigationController的子视图控制器可以吗? (我最初尝试使用带有自定义视图的右侧栏按钮项,但是this question中所述,项目与屏幕右侧之间存在间隙。)
答案 0 :(得分:3)
正如亚特提到的,将其他视图控制器视图添加为子视图是一种糟糕的方法。您应该考虑使用子视图控制器属性。我添加了一个示例来添加(和删除)视图控制器到导航控制器:
- (void)addToNavigationControllerViewController:(UIViewController *)controller
{
[controller willMoveToParentViewController:self.navigationController];
[self.navigationController addChildViewController:controller];
controller.view.frame = self.navigationController.view.bounds;
[self.navigationController.view addSubview:controller.view];
[controller didMoveToParentViewController:self.navigationController];
}
- (void)removeFromParentViewControllerChildViewController:(UIViewController *)controller
{
// dismissing a View Controller from it's Parent View Controller
[controller willMoveToParentViewController:nil];
[controller.view removeFromSuperview];
[controller removeFromParentViewController];
[controller didMoveToParentViewController:nil];
controller = nil;
}