Customize navigation bar with title view

前端 未结 8 2271
一生所求
一生所求 2020-12-08 13:41

I am trying to add a custom view in the center of a navigation bar and I am using the following code to test it:

UIView * testView = [[UIView alloc] init];
[         


        
相关标签:
8条回答
  • 2020-12-08 14:25

    This works. Give frame at the time of initialisation

     UIView *iv = [[UIView alloc] initWithFrame:CGRectMake(0,0,32,32)];
     [iv setBackgroundColor:[UIColor whiteColor]];
      self.navigationItem.titleView = iv;
    
    0 讨论(0)
  • 2020-12-08 14:27

    Swift 3/4

    You may set i.e. UILabel as a titleView. Call it in viewDidLoad():

    private func setNavigationTitle(_ title: String) {
        navigationItem.title = nil // clear the default title
        let titleLabel = UILabel() // you don't need to specify a frame, it will be centred in the navbar
        titleLabel.font = ...
        titleLabel.textColor = ...
        titleLabel.text = title
        titleLabel.backgroundColor = .clear
        navigationItem.titleView = titleLabel
        navigationTitleView = titleLabel // you may create a property if you want to manipulate the title view later
    }
    

    Note navigationItem.title = nil, otherwise title may override titleView.

    0 讨论(0)
提交回复
热议问题