Home > Net >  SwiftUI dissmiss sheet with WKWebView UIViewRepresentable
SwiftUI dissmiss sheet with WKWebView UIViewRepresentable

Time:05-05

today I facing one problem and it seems to be bug for me, I m unable to dismiss sheet when clicked on button inside of sheet, funny is that when I swipe down modal It dismiss, but only when I want dismiss on action it doesn't work at all

iOS 15.4.1 real device and simulator

I tried \.dismiss, \.presentationMode, but without success

my WebView Representable struct

import SwiftUI
import WebKit

struct WebView: UIViewRepresentable {
    
    let url: URL?
    
    func makeUIView(context: Context) -> WKWebView {
        let prefs: WKWebpagePreferences = WKWebpagePreferences()
        prefs.allowsContentJavaScript = true
        
        let config: WKWebViewConfiguration = WKWebViewConfiguration()
        config.defaultWebpagePreferences = prefs
        
        return WKWebView(frame: .zero, configuration: config)
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        guard let myURL = url else {
            return
        }
        let request = URLRequest(url: myURL)
        uiView.load(request)
    }
}

sheet modifier is here

.sheet(isPresented: $showWebViewSheet) {
                ZStack {
                    // webview
                    WebView(url: URL(string: webViewURL))
                    
                    // dissmiss
                    Button(action: {
                        dismiss()
                    }) {
                        Image(systemName: "xmark")
                            .padding(10)
                            .background(Color.gray.opacity(0.5))
                            .cornerRadius(20)
                            .padding(30)
                    }
                }
            }

CodePudding user response:

A button with dismiss() won't work. Try this code implementation:

.sheet(isPresented: $showWebViewSheet) {
                ZStack {
                    // webview
                    WebView(url: URL(string: webViewURL))
                    
                    // dissmiss
                    Button(action: {
                        showWebViewSheet = false
                    }) {
                        Image(systemName: "xmark")
                            .padding(10)
                            .background(Color.gray.opacity(0.5))
                            .cornerRadius(20)
                            .padding(30)
                    }
                }
            }
  • Related