简体   繁体   中英

iOS: Make function calls between UIViewRepresentable and View both ways, SwiftUI

I am building an application where one of the pages has a webview. Currently the page has a the webview representable and a view. Webview is brought to the view using the UIViewControllerRepresentable. I am wondering firstly how when I tap the login button can I call a function inside the LoginWebview, and also secondly vice versa, how can I call a function in the LoginView from the LoginWebview. I currently have the set up so that when I click login it toggles the states which causes the updateUIView to trigger but how can I call a custom made function in there? And vice versa

Apologies for the long description above and if this a stupid question

Thanks:)

LoginView:

import SwiftUI
import WebKit

struct LoginView: View {
    
    @State public var email: String = ""
    @State public var password: String = ""
    let verticalPaddingForForm = 40
    @State private var willMoveToNextScreen = true
    

    @Binding var isLoggedIn: Bool
    
    @State var showJSAlert = false
    
    
    var body: some View {
            
        LoginWebview(testdo: self.showJSAlert)
        
        ZStack {
            
            Color(red: 20/225.0 ,green: 22/225.0 , blue: 25/225.0)
            
            VStack(alignment: .leading, spacing: 0) {
                Image("logo")
                    .resizable()
                    .scaledToFit()
                    .padding(.top, 150)
                    .padding()
            }
            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading)
            .ignoresSafeArea(.all)
            
            VStack(spacing: CGFloat(verticalPaddingForForm)) {
                                
                VStack {
                        TextField("Email", text: $email)
                            .padding(.horizontal, 15).padding(.top, 50)
                        Divider()
                            .padding(.horizontal, 15)
                        SecureField("Password", text: $password)
                            .padding(.horizontal, 15).padding(.top, 20)
                        Divider()
                            .padding(.horizontal, 15)

                }
                .background(Color(.white))
            
                
                Button(action: {
                    
                    //Calls login webview and triggers update that calls the js
                    self.showJSAlert.toggle()

                }) {
                    Text("Login")
                        .padding()
                        .font(.system(size: 20))
                    
                }
                .background(Color.black)
                .foregroundColor(Color.white)
                .cornerRadius(10)
                .padding(.top, 0)
                .padding(.bottom, 20)
                
            }
            .padding(.horizontal, CGFloat(verticalPaddingForForm))
            .background(Color(.white))
            
            VStack{
                Spacer()
                Button(action: {
                    
                }) {
                    Text("Register")
                        .padding()
                        .font(.system(size: 40))

                    
                }
                .background(Color(red: 20/225.0 ,green: 22/225.0 , blue: 25/225.0))
                .foregroundColor(Color.white)
                .cornerRadius(10)
                .padding()
            }
        }.ignoresSafeArea()
    };

LoginWebview:

import SwiftUI
import WebKit

struct LoginWebview: UIViewRepresentable {
    var testdo = false

    
    func makeUIView(context: UIViewRepresentableContext<LoginWebview>) -> WKWebView {
                
        let preferences = WKPreferences()

        let configuration = WKWebViewConfiguration()
        configuration.preferences = preferences

        let userContentController = WKUserContentController()

        userContentController.add(context.coordinator, name:"observer")

        configuration.userContentController = userContentController
        
        let webView = WKWebView(frame: .zero, configuration: configuration)
        webView.navigationDelegate = context.coordinator
        

        let url = URL(string: "https://www.google.co.uk")!
        webView.load(URLRequest(url: url))
        return webView
    }
  
    func updateUIView(_ uiView: WKWebView, context: UIViewRepresentableContext<LoginWebview>) {
        print(testdo)
        
        print("Controller")
        uiView.evaluateJavaScript("sendComment();")
        print(UserDefaults.standard.string(forKey: "Token") ?? "")
            }
    

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    func printstuff() {
        print("printstuff")
    }
    
  
    typealias UIViewType = WKWebView
}





class Coordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
    
    var control: LoginWebview
    
    init(_ control: LoginWebview) {
        self.control = control
    }
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        showAlert(body: message.body)
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
    }
    
    func sendjs(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    }
    
    func showAlert(body: Any) {
        print("working")
    }
    
}

You can use computed property and closure for a callback.

Here is the example code.

struct LoginView: View {
    
    // Other code
    
    // Webview var
    private var webView: LoginWebview {
        LoginWebview(testdo: self.showJSAlert) {
            // Here you will get the call back
            print("Callback")
        }
    }
    
    var body: some View {
        
        webView // <-- Here
        
        // Other Code

And for button action

Button(action: {
    
    //Calls login webview and triggers update that calls the js
    self.showJSAlert.toggle()
   // Access your function
    self.webView.printstuff()
    
}) {
    Text("Login")
        .padding()
        .font(.system(size: 20))
    
}

And in LoginWebview

struct LoginWebview: UIViewRepresentable {
    var testdo = false
    
    var callBack: (() -> Void)? = nil
class Coordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
    // Other code
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.control.callBack?() // < Example for calling callback
    }
    
    // Other code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM