什么时候应该设计我的UINavigationBar?

问题描述:

我有一个视图控制器具有设计UINavigationBar的,它从视图控制器继承并调用它的设计方法和ShowingViewController和SecondViewController从SubViewController继承SubViewController的方法。什么时候应该设计我的UINavigationBar?

ShowingViewController是UINavigationController的根控制器,并执行“显示”塞格到SecondViewController。 它们都具有NSString属性“presentingProperty”。 ViewController将自定义titelView设置为显示属性字符串的导航栏。

我的问题:我应该在哪里调用视图控制器的设计方法?

当我把它称为viewWillLoad,当我切换到SecondViewController因为该方法改变了“老” ShowingViewController的导航栏,我将无法正常工作。

当我把它在viewDidLoad中,用户将看到之前的非故意导航栏。

我的设计方法的代码:

if (self.navigationController.navigationBar) { 
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 21)]; 
    NSMutableAttributedString *titleText = [[NSMutableAttributedString alloc] initWithString:self.presentingProperty]; 
    [titleText addAttribute: NSForegroundColorAttributeName value: [UIColor whiteColor] range: NSMakeRange(0, self.presentingProperty.length)]; 
    [titleText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Avenir-Heavy" size:21] range:NSMakeRange(0, self.presentingProperty.length)]; 
    [titleLabel setTextAlignment:NSTextAlignmentCenter]; 
    [titleLabel setAttributedText: titleText]; 
    [self.navigationController.navigationBar.topItem setTitleView:titleLabel]; 
} 

谢谢您的帮助。

您应该建立于titleview了的导航栏在:

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

    <your titleView code here> 
} 

这就是所谓的后viewDidLoad中上的第一次,当其他ViewControllers高于当前一个被弹出导航后来被称为叠加。该视图控制器生命周期的良好状态图可以在文档在https://developer.apple.com/documentation/uikit/uiviewcontroller#1652793

被发现在一个风格的时候,你还可以设置于titleview与此代码:

self.navigationItem.titleView = <your-view>; 

你可以试试这个。

- (void)viewDidLoad 
{ 
     self.navigationItem.titleView = <your titleView> 
} 
- (void)viewWillLayoutSubviews 
{ 
    <your titleView>.frame = CGRectMake(....) 
}