Static/fixed Navigation Bar in iOS

徘徊边缘 提交于 2019-12-29 07:55:12

问题


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?


回答1:


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.

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.

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,

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


来源:https://stackoverflow.com/questions/51486867/static-fixed-navigation-bar-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!