问题
In viewcontroller, I'm loading a webview(WKWebview) with large navigation title enabled. The problem is its showing the large navigation bar and title perfectly before the webview gets loaded once the webview got loaded it shrinks to normal. Anyhelp would be appreciated.
Thanks in advance...!
回答1:
Swift4, Swift5 :
- The reason of this issue is your navigationBar height is changing when you webView starts loading the page. so using
viewLayoutMarginsDidChange()we can change navigationBar height. viewLayoutMarginsDidChange()Called to notify the view controller that the layout margins of its root view changed. This method will get called every time when navigationBar height changes.
Below code worked for me
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
private var webView: WKWebView!
var didChange = false //Set true when we have to update navigationBar height in viewLayoutMarginsDidChange()
override func viewLayoutMarginsDidChange() {
if didChange {
print("Height : - \(self.navigationController?.navigationBar.frame.size.height)")
// set NavigationBar Height here
self.navigationController!.navigationBar.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 96.0)
didChange.toggle()
}
}
override func viewDidLoad() {
super.viewDidLoad()
let appearance = UIBarButtonItem.appearance()
appearance.setBackButtonTitlePositionAdjustment(UIOffset.init(horizontal: 0.0, vertical: -60), for: .default)
self.navigationItem.title = "WebView"
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.navigationBar.tintColor = UIColor.black
self.navigationController?.navigationBar.prefersLargeTitles = true
webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
webView.navigationDelegate = self
view = webView
let myURL = URL(string:"https://google.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print("Did Start")
//webView page starts loading
didChange = true
}
}
来源:https://stackoverflow.com/questions/53728599/navigation-bar-with-large-title-shrinks-when-webview-is-loaded