Skip to content

Instantly share code, notes, and snippets.

@revblaze
Created January 12, 2021 16:01
Show Gist options
  • Save revblaze/d3d5cb5efe55736bd42db78b6f6a5747 to your computer and use it in GitHub Desktop.
Save revblaze/d3d5cb5efe55736bd42db78b6f6a5747 to your computer and use it in GitHub Desktop.
Quick workaround for forcing large titles in UINavigationBar when working with an embedded WKWebView
/**
Quick workaround to fix UINavigationBar from automatically entering the default display style with a WKWebView object (despite being set to `prefersLargeTitles = .always`).
This works by first allowing WKWebView to take priority over the UINavigationBar, and then simulating user-scroll interaction to re-enable it.
*/
func adjustNavBarScroll() {
// webView.scrollView.bounces = false
// Scroll to make UINavigationBar title small (update with accurate properties)
let scrollPoint = CGPoint(x: 0, y: 100)
webView.scrollView.setContentOffset(scrollPoint, animated: false)
// Scroll 1 pixel above UINavigationController to activate Large Title
_ = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: false) { timer in
let scrollPoint = CGPoint(x: 0, y: -1)
self.webView.scrollView.setContentOffset(scrollPoint, animated: false)
// Scroll to origin point
_ = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: false) { timer in
let scrollPoint = CGPoint(x: 0, y: 0)
self.webView.scrollView.setContentOffset(scrollPoint, animated: false)
// View is ready to display ViewController with fixed large UINavigationBar
}
}
}
@revblaze
Copy link
Author

When working with hybrid apps, I constantly found myself running into this issue with frustration. I want my hybrid apps to feel as native as possible, and that includes as many native aspects from Apple's Human Design Guide as possible.

Problem

When attempting to enable UINavigationBar's prefersLargeTitles = .always alongside a WKWebView object, the UINavigationBar will always shrink back to its default display size upon WKWebView firing the .didFinish method.

Workaround

When the user initiates the scrolling of the loaded WKWebView, and then scrolls back to the top, it re-enables the large title UINavigationBar. This workaround essentially simulates this behaviour, programatically, and without the need for user interaction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment