Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have enabled large titles for the navigation bar with:

navigationController?.navigationBar.prefersLargeTitles = true

This makes the navigation bar start with an expanded height, and shrink as the user scrolls down.

Now, I want to add a subview inside the navigation bar that resizes, based on how tall the navigation bar is. To do this, I will need to get both the maximum and minimum height of the navigation bar, so I can calculate the fraction of how much it's expanded.

I can get the current height of the navigation bar like this:

guard let height = navigationController?.navigationBar.frame.height else { return }
print("Navigation height: (height)")

I'm calling this inside scrollViewDidScroll, and as I'm scrolling, it seems that the expanded height is around 96 and the shrunk height is around 44. However, I don't want to hardcode values.

iPhone 12

Expanded (96.33) Shrunk (44)
enter image description here enter image description here

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
594 views
Welcome To Ask or Share your Answers For Others

1 Answer

Using following extension u can get extra height

extension UINavigationBar
{
    var largeTitleHeight: CGFloat {
        let maxSize = self.subviews
            .filter { $0.frame.origin.y > 0 }
            .max { $0.frame.origin.y < $1.frame.origin.y }
            .map { $0.frame.size }
        return maxSize?.height ?? 0
    }
} 

And I said earlier u can get extended height by following

guard let height = navigationController?.navigationBar.frame.maxY else { return }
print("Navigation height: (height)")

let window = UIApplication.shared.keyWindow
let topPadding = window?.safeAreaInsets.top

let extendedHeight = height - topPadding

You can get shrunk height by subtracting difference from extended height

guard let difference = navigationController?.navigationBar.lagreTitleHeight else {return}
let shrunkHeight = extendedHeight - difference 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...