WebView

I am trying to parse some html inside my app. Not an entire html page, but just few blocks of html code. So I'm using Ink package for that.

// FIRST I HAVE A WEBVIEW
import SwiftUI
import WebKitstruct WebView : UIViewRepresentable {
  var html: String  func makeUIView(context: Context) -> WKWebView {
    return WKWebView()
  }  func updateUIView(_ webView: WKWebView, context: Context) {
    webView.loadHTMLString(html, baseURL: nil)
  }}
// IN HERE I'M PARSING THE HTML AND ALSO ADDING SOME STYLING TO IT
import Foundation
import Ink
class ParseContent: ObservableObject {
  var markdown: String = ""  

  func parse() -> String {
    let parser = MarkdownParser()
    let html = parser.html(from: markdown)      
    let htmlStart = "<HTML><HEAD></HEAD><BODY style=\"padding: 140px; font-size: 120px; font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Open Sans,Helvetica Neue,sans-serif\">"
    let htmlEnd = "</BODY></HTML>"      
    return htmlStart + html + htmlEnd
  }
}
// IN HERE I AM JUST USING MY PREVIOUSLY CREATED WEBVIEW
WebView(html: myHtmlContent)
    .onAppear() {
        htmlContent = ParseContent().parse()
    }

So here are my questions:

  1. Why the styling isn't working since I am concatenating the html ? I see it in a lot of tutorials but cant understand why not working.

  2. I would like to have the font inside my WebView, the same as I have for my other components like Text("abc") so I would keep a pattern and the visitor woudnt realize they are different components.

  3. How to set the WebView without a vertical scroll ? Keeping the entire height coming from the parsed html ?

Thank you guys :)

Your HTML is static / hardcoded right?

  1. Put all the HTML into a single variable (get rid of the empty markdown string)
  2. Call parser.html() on that variable.
  3. Pass the return value from parser.html() into loadHTMLString()

Do all of steps 1 - 3 directly inside of the updateUIView() function. I'm not sure why you havethe ParseContent class. Just get rid of it.

Something like this...

import SwiftUI
import WebKit


struct HardCodedWebView: UIViewRepresentable {

    let markdown: String

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

    func updateUIView(_ uiView: WKWebView, context: Context) {

        let htmlStart = "<HTML><HEAD></HEAD><BODY style=\"padding: 140px; font-size: 120px; font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Open Sans,Helvetica Neue,sans-serif\">"
        let htmlEnd = "</BODY></HTML>"

        let html = htmlStart + markdown + htmlEnd

        uiView.loadHTMLString(html, baseURL: nil)
    }

}



struct HardCodedWebView_Previews: PreviewProvider {
    static var previews: some View {
        let markdownExample = "**random markdown text**"
        HardCodedWebView(markdown: markdownExample)
    }
}

FYI a regular Text() will render markdown directly.

WebView
 
 
Q