WKWebView in Interface Builder

前端 未结 12 857
南旧
南旧 2020-11-30 01:51

It seems that the IB object templates in XCode 6 beta are still creating old-style objects (UIWebView for iOS and WebView for OSX). Hopefully Apple will update them for the

12条回答
  •  时光取名叫无心
    2020-11-30 02:46

    Info.plist

    add in your Info.plist transport security setting

     NSAppTransportSecurity
     
        NSAllowsArbitraryLoads
        
     
    

    Xcode 9.1+

    Using interface builder

    You can find WKWebView element in the Object library.

    Add view programmatically with Swift 5

    let webView = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
    view.addSubview(webView)
    webView.translatesAutoresizingMaskIntoConstraints = false
    webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
    webView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true
    webView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
    webView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor).isActive = true
    

    Add view programmatically with Swift 5 (full sample)

    import UIKit
    import WebKit
    
    class ViewController: UIViewController {
    
        private weak var webView: WKWebView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            initWebView()
            webView.loadPage(address: "http://apple.com")
        }
    
        private func initWebView() {
            let webView = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
            view.addSubview(webView)
            self.webView = webView
            webView.translatesAutoresizingMaskIntoConstraints = false
            webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
            webView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true
            webView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
            webView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor).isActive = true
        }
    }
    
    extension WKWebView {
        func loadPage(address url: URL) { load(URLRequest(url: url)) }
        func loadPage(address urlString: String) {
            guard let url = URL(string: urlString) else { return }
            loadPage(address: url)
        }
    }
    

提交回复
热议问题