如何通过UIViewRepresentable访问goBack和goForward

时间:2019-06-25 18:30:44

标签: wkwebview swiftui ios13

我通过UIVewRepresentable在SwiftUI中添加了WKwebview。我很难获得一些按钮来使Web视图后退和前进。下面是我制作的两个类,但我什至没有打印出来(也许是个错误?)。

import SwiftUI

import WebKit

struct Webview : UIViewRepresentable {

let request: URLRequest

func makeUIView(context: Context) -> WKWebView  {
    return WKWebView()
}

func updateUIView(_ uiView: WKWebView, context: Context) {
    uiView.load(request)
}

func goBack(){
    // go back
    print("go back")
}

func goForward (){
    // go forward
    print("go forward")
}
}



import SwiftUI

struct FullWebView : View {

let webview = Webview(request: URLRequest(url: URL(string: "https://www.apple.com")!))

var body: some View {
    VStack{
        HStack{
            Button(action: {
                //do something
                self.webview.goBack()
            }){
                Text("back")
            }

            Spacer()

            Button(action: {
                //do something
                self.webview.goForward()
            }){
                Text("forward")
            }

        }

        webview
    }
}
}

1 个答案:

答案 0 :(得分:1)

dfd感谢您将我指向正确的路径,您的答案需要进行一些修改,因为将webview作为var添加到struct意味着我需要在使用它时为其设置值,因此我还必须添加自定义init方法。无论如何,这里是有效的代码。

Webview结构

import SwiftUI

import WebKit

struct Webview : UIViewRepresentable {


    let request: URLRequest
    var webview: WKWebView?

    init(web: WKWebView?, req: URLRequest) {
        self.webview = WKWebView()
        self.request = req
    }

    func makeUIView(context: Context) -> WKWebView  {
        return webview!
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.load(request)
    }

    func goBack(){
        webview?.goBack()
    }

    func goForward(){
        webview?.goForward()
    }
  }

这是使用网络视图并将按钮添加到顶部的结构

import SwiftUI

struct FullWebView : View {


let webview = Webview(web: nil, req: URLRequest(url: URL(string: "https://www.apple.com")!))

var body: some View {
    VStack{
        HStack{
            Button(action: {
                //do something
                self.webview.goBack()
            }){
                Text("back")
            }

            Spacer()

            Button(action: {
                //do something
                self.webview.goForward()
            }){
                Text("forward")
            }

        }

        webview
    }
}
}