7

I'm adding a custom titleView inside a navigation bar using navigationItem.titleView for both Master/Detail VC. On changing the orientation of the device to landscape, titleView under MasterViewController works fine, but for DetailViewController titleView disappears. On changing the orientation back to portrait titleView appears back for DetailViewController. I have also attached a link for source code and video.

Is this an intended behavior or am I making a mistake from my side or is it an issue from Apple's side ?

//Custom Title View:
class TitleView: UIView {
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        return CGSize(width: 50, height: 20)
    }
}

class DetailViewController: UIViewController {
    override func viewDidLoad() {
       super.viewDidLoad()
       //Adding titleView for Master/Detail VC:
       navigationItem.titleView = {
            //Setting frame size here, did not make any difference
            let view = TitleView(frame: .zero)
            view.backgroundColor = .red
            return view
       }()
    }
}

Full source code here: https://github.com/avitron01/SplitViewControllerIssue/tree/master/MathMonsters

Video highlighting the issue: https://vimeo.com/336288580

Marwen Doukh
  • 1,946
  • 17
  • 26
Avinash
  • 113
  • 1
  • 9
  • Seems like this post turned out to be a dud :( – Avinash May 27 '19 at 12:26
  • Similar issue can be observed when the app is running on iPad in multitasking env (with another app side by side). When you change the app to compact and back to regular width the custom title view is gone. – Wei WANG May 08 '20 at 00:53
  • Wondering if you found a reasonable solution for this? Having the same problem on iOS 13 – Petar Jul 14 '20 at 21:37

2 Answers2

1

I had the same issue. It seems an iOS bug. My workaround was to reassign the title view on every view layout. I used this piece of code in my DetailViewController:

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    if let v = navigationItem.titleView {
        navigationItem.titleView = nil
        navigationItem.titleView = v
    }
}
Sergio
  • 49
  • 2
  • This works for me. It works for my case where the app is in multitask mode on iPad and the custom title view on DetailViewController will disappear when it's toggled between compact/regular modes. – Wei WANG May 08 '20 at 01:03
0

For those who stumble upon this, see also iOS 11 navigationItem.titleView Width Not Set. Basically, there's two suggested workarounds:

  • use a custom UIView that tells iOS to treat its intrinsicContentSize to be as big as possible with UIView.layoutFittingExpandedSize
  • use widthAnchor/heightAnchor constraints to set width and height of your view
qix
  • 7,228
  • 1
  • 55
  • 65