Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static/fixed Navigation Bar in iOS

I have a Navigation Controller and a Collection View under it inside my app. And there is a problem: I use large title inside my Navigation bar, so everything inside is not static. When I scroll the collection view cells, the title (I created it manually using UILabel() to move it as I want inside the navigation bar) and buttons move up and the navigation bar takes form of iOS 10 navigation bar, I mean its height. You can see it here:

The normal state of my Navigation Bar with "Prefer large titles" On:

It happens when I scroll my Collection View, everything goes up:

So the question is simple: how to make the force constant height for the navigation bar? I want it to become fixed even while scrolling. Are there any ideas? Is it possible?

And the second question, if the first is impossible: Another solution for my problem is to make the Navigation Bar with "Prefer large titles" Off bigger. I tried this code:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    let height: CGFloat = 50 //whatever height you want to add to the existing height
    let bounds = self.navigationController!.navigationBar.bounds
    self.navigationController?.navigationBar.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height + height)
}

but it worked only for large titles. So how can I make the navigation bar bigger?

like image 905
Egor Iskrenkov Avatar asked Jul 23 '18 20:07

Egor Iskrenkov


1 Answers

Yes, you can make it fixed. It will not scroll if the very first view in the view hierarchy is not a CollectionView/TableView (ScrollView).

Using Storyboard/Xib:

Consider the following image where a tableView and button are added in scene. Here the navigation bar will collapse on scroll of tableView because tableView is the very first view in viewController's containerView hierarchy attached to the navigation bar.

enter image description here

Now to make the navigation bar fixed, if we just change the order of tableView and button as below, it will disable the collapsing of navigation bar.

enter image description here

To change the order of the view, you have to click, hold and move up/down.

If you have only CollectionView in this scene then you can add a placeholder view at the top and set its height to zero as below,

enter image description here

Programmatically:

If you are setting up view's programmatically then you just need to add a placeholder view at the top or add tableView/collection after adding other views.

e.g,

self.view.addSubview(UIView(frame: .zero))
self.view.addSubview(tableView) // or collectionView
like image 113
Kamran Avatar answered Oct 04 '22 00:10

Kamran