Navigation bar titleView alignment

11,004

Solution 1

The thing is, navigation titleView always try to center your view. The reason that the title you see off-center in a smaller screen is that, the width of your custom titleView has gone beyond the maxmium width of titleView.

If you set the value to 160, you will see it centered for the second situation.

General Solution

If you want to adapt title width to different devices, there are a few approaches that may help you solve the problem.

  1. Set different width based on different screen width. For example, when screen width is 320, set it no more than 160. If larger than 320, assign value based on different screen size. This is not an elegant solution, but pretty much straightforward without banging your head into setting and trying complicated constraints.

  2. Calculate the actual width of titleView. The width of titleView is determined by navigation bar width minus left and right barbuttonitem. Something like

TitleViewWidth = Navigation width - leftbarbuttonitem.width +/- rightbarbuttonitem.width - someConstant

You need a little bit experiment for finding the appropriate constant that fits this formula.

  1. Create a xib file for this titleView, set up constraints more flexibly than claim a fixed width. Load view from xib and then assign to titleView. This may cost longer time to tune it to work.

Edit

I think of another way that may be easier for you if you are new to this.

In the storyboard, find and drop a view to this view controller's navigation bar titleView area.

Expand however long you want the view to be.

Drop two labels to that view, and set the leading and trailing and height and vertical constraints.

How it looks on storyboard

storyboard image

How it runs on 4S

4S running

Solution 2

Approach:

  • titleView is always centred
  • So set your custom view's width to match that of the navigationBar (width -40)

Code

private func setupNavigationItems() {
    
    let label = UILabel()
    
    label.translatesAutoresizingMaskIntoConstraints = false
    
    label.text = "aaaaa"
    label.backgroundColor = .green
    
    label.textAlignment = .left
    
    navigationItem.titleView = label
    
    if let navigationBar = navigationController?.navigationBar {
        
        label.widthAnchor.constraint(equalTo: navigationBar.widthAnchor, constant: -40).isActive = true
    }
}

Custom Title View for the entire width of the navigation bar

Share:
11,004
Salihcyilmaz
Author by

Salihcyilmaz

asdf,jn,khk,klhlkjlklo;klkp;lihkgupk;p'oo [ p[p ] [l';k;oj;;k;kj; 'pkl;;l

Updated on June 26, 2022

Comments

  • Salihcyilmaz
    Salihcyilmaz almost 2 years

    I want my navigation bar to show two things in the middle. One them is going to be List name, and the other one will be name of users. User names will be placed under list name. What i have done so far is, i created two label and one superview programatically and set the titleView of navigationItem.

    override func viewDidLoad() {
            super.viewDidLoad()
            var rectForView = CGRect(x: 0, y: 0, width: 190, height: 176)
            var viewForTitle = UIView(frame: rectForView)
    
            var rectForNameLabel = CGRect(x: 0, y: 63, width: 190, height: 30)
            var listNameLabel = UILabel(frame: rectForNameLabel)
            listNameLabel.text = "Name of the List...."
            listNameLabel.textAlignment = NSTextAlignment.Center
            listNameLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 15)
    
            var rectForListLabel = CGRect(x: 0, y: 93, width: 190, height: 20)
            var usersOfListLabel = UILabel(frame: rectForListLabel)
            usersOfListLabel.text = "some Users...."
            usersOfListLabel.textAlignment = NSTextAlignment.Center
            usersOfListLabel.font = UIFont(name: "HelveticaNeue", size: 10)
    
            viewForTitle.addSubview(listNameLabel)
            viewForTitle.addSubview(usersOfListLabel)
    
    
            self.navigationItem.titleView = viewForTitle
    

    The thing is, I'm picking width randomly, which leads to alignment problems in different devices. How to achieve middle alignment in my case? iphone 6

    iphone 5

  • Salihcyilmaz
    Salihcyilmaz about 9 years
    I thought something similar to solution mentioned in 1. But i couldn't figured out how can i do that... How can i set different quantity for different devices or screens? For number 3, i don't know how to create xib file. Im new to iOS and Apple seems to against creating nib files by referring to documentations in general. Can you give me some links about xibs or something like "go dive in to that documentation, learn these" ... Anyway, thanks for your interest.
  • Shali Liu
    Shali Liu about 9 years
    @Salihcyilmaz check my edit for a easier approach. For 1. you can try to use UIScreen or simply try to get the width of navigation bar, see what the number is, and assign different width based on different navigation width.
  • Shali Liu
    Shali Liu about 9 years
    @Salihcyilmaz For 3, I didn't find something handy right now. There're quite a few about how to create xib file or how to reuse xib file, I simply didn't know if there're really work for now :) Just search around reusable xib file if you need in the future.
  • Salihcyilmaz
    Salihcyilmaz about 9 years
    Nice one. Actually what you did in edit was storyboard version of mine, i guess. Anyway in both cases if i set width of view to 160, every things seems okay. Otherwise they start to move away from center. Can you explain why that happens?
  • Shali Liu
    Shali Liu about 9 years
    @Salihcyilmaz You don't need to code anything in viewdidload, if you have already set view up in storyboard with appropriate constraints.
  • Shali Liu
    Shali Liu about 9 years
    @Salihcyilmaz No problem :)
  • h-bomb
    h-bomb over 7 years
    Would you please explain what someConstant represents?
  • Shali Liu
    Shali Liu over 7 years
    @h-bomb I would suggest try the storyboard approach (after Edit), it's better practice moving forward.
  • h-bomb
    h-bomb over 7 years
    That's not an option. We are not using storyboards in our team project. So you can't explain what someConstant represents?
  • Shali Liu
    Shali Liu over 7 years
    @h-bomb Basically iOS has updated a lot since last year. But basically it's just a number. You can start from 0 and then increase or decrease based on the position you observed. Not sure it's working well with all the devices now.
  • h-bomb
    h-bomb over 7 years
    Yeah - ran into an issue with a particular device. Thanks!
  • Keyhan Kamangar
    Keyhan Kamangar over 3 years
    You saved my day! Thank you so much.