Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WKwebview content covers the top status bar

I followed this tutorial to create a WKwebview which worked but with one problem. The top status bar is covered by the content of the webView.

Since the webView IS the containerView, how then can the webView go under the status bar in code. Thanks

import UIKit
import WebKit

class ViewController: UIViewController {
@IBOutlet var mainView : UIView?
var webView: WKWebView?

override func loadView() {
    super.loadView() // call parent loadView
    self.webView = WKWebView() // instantiate WKWebView
    self.view = self.webView! // make it the main view
}

override func viewDidLoad() {
    super.viewDidLoad() // run base class viewDidLoad
    let url = NSURL(string:"https://www.google.com") // make a URL
    let req = NSURLRequest(URL:url!) // make a request w/ that URL
    self.webView!.loadRequest(req) // unwrap the webView and load the request.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

enter image description here}

like image 976
Fred J. Avatar asked Oct 17 '25 07:10

Fred J.


2 Answers

Here's what ended up working for me (very similar to Herbert Bay's answer).

Swift:

class ViewController: UIViewController, WKNavigationDelegate {

    let webView = WKWebView()

    override func viewDidLoad() {
        // Get height of status bar (iPhone X introduced a new status bar)
        let statusBarHeight = UIApplication.shared.statusBarFrame.height
        // Initialize the frame
        webView.frame = CGRect.init(x: 0, y: statusBarHeight, width: view.bounds.maxX, height: view.bounds.maxY)
        // Set background color of status bar (optional)
        self.view.backgroundColor = UIColor(red: 248/255.0, green: 248/255.0, blue: 248/255.0, alpha: 1.0)
    }
}

Setting y in CGRect.init() to the height of the status bar eliminates any overlapping of your web view and the status bar.

like image 79
wnd Avatar answered Oct 18 '25 22:10

wnd


I would add the WKWebView as subview of the container view and use the size of the status bar to init the WKWebView with initWithFrame. Happy to learn if there is a better approach.

WKWebViewConfiguration *webViewConfiguration = [[WKWebViewConfiguration alloc] init];
CGFloat heightStatusBar = [UIApplication sharedApplication].statusBarFrame.size.height;
self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0.0, heightStatusBar,
                                                           self.view.frame.size.width,
                                                           self.view.frame.size.height-heightStatusBar)
                                  configuration:webViewConfiguration];
[self.view addSubview:_webView];
like image 30
Herbert Bay Avatar answered Oct 18 '25 20:10

Herbert Bay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!