簡體   English   中英

iOS:在 UIViewRepresentable 和 View 之間進行 function 調用,SwiftUI

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

我正在構建一個應用程序,其中一個頁面具有 webview。 目前該頁面有一個 webview 表示和一個視圖。 使用 UIViewControllerRepresentable 將 Webview 帶到視圖中。 我首先想知道當我點擊登錄按鈕時如何在 LoginWebview 中調用 function,其次反之亦然,如何從 LoginWebview 在 LoginView 中調用 function。 我目前已經進行了設置,因此當我單擊登錄時,它會切換導致 updateUIView 觸發的狀態,但是我如何在其中調用定制的 function? 反之亦然

為上面的冗長描述道歉,如果這是一個愚蠢的問題

謝謝:)

登錄視圖:

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()
    };

登錄網頁視圖:

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")
    }
    
}

您可以將計算屬性和閉包用於回調。

這是示例代碼。

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

對於按鈕動作

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))
    
}

並在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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM