Search code examples
iosswiftuinavigationcontroller

iOS: Full width custom titleView of navigation bar flickers during interactive pop gesture of UINavigationController


I want to use a custom titleView for my navigation controller which occupies available width in navigation bar. To achieve this I'm using a custom view with UIView.layoutFittingExpandedSize as it's intrinsicContentSize. But due to this layoutFittingExpandedSize the title view flickers during interactive pop gesture of UINavigationController. (Please see attached GIF: https://ibb.co/98hC3rc )

Note: I'm having a default navigation back bar button and a custom right bar button item.

  • This can be fixed if the title view has fixed width. But calculating the available space for title view in navigation bar is not possible.
  • I've also tried toggling translatesAutoresizingMaskIntoConstraints flag in view controller life cycle method, but it does not work.
class ProfileVC: UIViewController {
    override func viewWillAppear(_ animated: Bool) {
        let searchBox = SearchView(frame: .zero)
        self.navigationItem.titleView = searchBox

        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: nil, action: nil)
    }
}

class SearchView: UIView {
    override var intrinsicContentSize: CGSize {
        return UIView.layoutFittingExpandedSize
    }
}

Could anyone help me solve this title view flickering issue? Thanks in advance!


Solution

  • Eventually I found a solution to this. The interactive pop gesture starts at viewWillDisappear: and ends at viewWillAppear:. Step 1: switch on translatesAutoresizingMaskIntoConstraints for navigation title view when interaction starts(i.e. in viewWillDisappear:) so that the width and position of title view remains constant. Step 2: switch off translatesAutoresizingMaskIntoConstraints for navigation title view when interaction stops(i.e. in viewWillAppear:) so that the existing constraints will work as it is.