【问题标题】:When should I design my UINavigationBar?我应该什么时候设计我的 UINavigationBar?
【发布时间】:2017-10-20 11:22:17
【问题描述】:

我有一个 ViewController,它有一个设计 UINavigationBar 的方法,一个继承自 ViewController 并调用其设计方法的 SubViewController,以及一个继承自 SubViewController 的 ShowingViewController 和一个 SecondViewController。

ShowingViewController 是 UINavigationController 的根控制器,它对 SecondViewController 执行“显示”Segue。 它们都有 NSString 属性“presentingProperty”。 ViewController 为显示属性字符串的导航栏设置了一个自定义的 titleView。

我的问题:我应该在哪里调用 ViewController 的设计方法?

当我在viewWillLoad中调用它时,我切换到SecondViewController时将无法工作,因为该方法改变了“旧” ShowingViewController的NavigationBar。

当我在 viewDidLoad 中调用它时,用户会看到之前未设计的 NavigationBar。

我的设计方法代码:

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];
}

感谢您的帮助。

【问题讨论】:

    标签: ios objective-c uinavigationbar


    【解决方案1】:

    你可以试试这个。

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

    【讨论】:

      【解决方案2】:

      您应该在以下位置为导航栏设置 titleView:

      - (void)viewWillAppear:(BOOL)animated {
          [super viewWillAppear: animated];
      
          <your titleView code here>
      }
      

      这在第一次 viewDidLoad 之后调用,稍后在当前视图控制器之上的其他视图控制器从导航堆栈中弹出时调用。 ViewController 生命周期的良好状态图可以在https://developer.apple.com/documentation/uikit/uiviewcontroller#1652793 的文档中找到

      在样式点上,也可以用这段代码设置titleView:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-07
        • 1970-01-01
        • 2021-09-07
        • 2021-05-23
        • 1970-01-01
        相关资源
        最近更新 更多