Search code examples
iosswiftmobileswiftuiwebkit

Is it possible to have a WKWebView open a web page which only occupies half the screen?


I am building an iOS app where part of the app is to be displayed as a Web View using WKWebView. Instead of opening the web page in a full screen, I want the WKWebView to cover only half the screen (like a floating native UI element) with the app in the background.

For reference, I want an experience something like https://social.msdn.microsoft.com//Forums/getfile/1679719 (image obtained from Google image search).

Is it possible to achieve this using WKWebView?

Side note: I was considering SFSafariViewController first and looks like it is not possible (at least not recommended) to have SFSafariViewController in this sort of setup.

I was not able to clearly confirm from the WKWebView documentation [1] or other Apple sources [2] if this was supported. As per [2],

You can present a full or partial view of web content directly in your app ...

But it was not clear if this is the same as the experience I was trying to build

References:

[1] https://developer.apple.com/documentation/webkit/wkwebview

[2] https://developer.apple.com/news/?id=trjs0tcd


Solution

  • Yes, it is possible to cover only have the screen with a WKWebView.

    Check this Post for SwiftUI possibilities.

    And here is a quick UIKit example:

    import UIKit
    import WebKit
    
    class ViewController: UIViewController {
    
         var webView: WKWebView!
         let url = URL(string: "https://www.google.com")!
    
         override func viewDidLoad() {
             super.viewDidLoad()
             view.backgroundColor = .red
             webView = WKWebView()
             webView.frame = CGRect(x: 0, y: view.frame.height / 2, width: 
             view.frame.width, height: view.frame.height / 2)
             view .addSubview(webView)
             webView.load(URLRequest(url: url))
         }
    }