Navigation bar with large title shrinks when webview is loaded

好久不见. 提交于 2019-12-04 11:00:37

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
    }

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