iosuinavigationbaruinavigationitemios16titleview

iOS 16 additional empty space in navigation item


When I creatе the simplest titleView with iOS 16 and add it to the navigationItem I see an additional space that I cannot remove in any way. I did not have this issue on iOS 15, does anybody know what can be done?

The issue I am trying to solve is that the titleView contains a label which gets misaligned on iOS 16. The label is on the most left side of the titleView and

I'm attaching a screenshot from iPhone 13 Pro Max - on the left is iOS 16 and on the right is iOS 15:

enter image description here

I have a view controller wrapped in a navigation controller and this is the only code in the view controller

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.titleView =  UIView(frame: CGRect(x: 0, y: 0, width: 404, height: 40)) 

        view.backgroundColor = .lightGray
        titleView.backgroundColor = .red
    }
}

The frame of the navigationItem.titleView:

iOS 15: iPhone 13 Pro Max: <UIView: 0x7f85fda14d10; frame = (0 0; 404 40);>
iOS 16: iPhone 13 Pro Max: <UIView: 0x7f7894f157e0; frame = (0 0; 388 40);>

I've tried removing insets, margins, changing the width, changing the place where I set the view, nothing works and I am out of ideas


Solution

  • I also had a problem with it, but I found a solution:

    1. You need to make your own class for TitleView
    2. You need to override intrinsicContentSize
    override var intrinsicContentSize: CGSize {
        return CGSize(width: UIScreen.main.bounds.width - (left/right margin),
                      height: (fixed height) )
    }
    

    So you will rely not on UIView.layoutFittingExpandedSize width/height but on your specific width/height.

    And if you just want to have it full width (like your screenshot) you can use UIScreen.main.bounds.width.

    If you want to have the same left/right margins on iOS 15 and iOS 16+ you can make UIScreen.main.bounds.width - (left/right margin).

    Here is the UI overview with issue Before and After fix:

    enter image description here