Create a custom navigationBar titleView using .xib

Keyhan Kamangar
Oct 30, 2020

Before iOS 11, we could easily create a custom titleView and set it as navigationBar’s titleView and it would adapt to the navigationBar width automatically. However, in iOS 11+ this is not working anymore and custom titleViews can’t automatically expand to the navigationBar’s width.

So, what should we do?

There are several solutions, like using autoLayout for customView widthAnchor or using CGRect to set its width according to navigationBar frame. However, neither of them work correctly.

After pushing to another viewController when you pop out the viewController, by using autoLayout you will see that the customTitleView frame has shrank to its default size. By using frame, we can easily achieve the result we want on iOS 13+ but for lower versions this doesn’t work.

Now, what can we do?

Well the answer is to use intrinsicContentSize. Since we are using a custom view with .xib file, we can easily override intrinsicContentSize in our CustomView class and return any size we want. For my project I wanted to set the width of the customView to be a little smaller than navigationBar width. So I returned CGSize(width: superview!.frame.width — 80, height: 40) for the size of intrinsicContentSize. If you want full width you can just remove the -80 or simply do:

override var intrinsicContentSize: CGSize {
return UIView.layoutFittingExpandedSize
}

Here is the full source code of my customTitleView. It contains a UISearchBar and a UIButton:

The result:

Custom titleView of navigationBar

Hope this can save you time and don’t forget to clap:)

--

--