Instantly Preview HTML Using a SwiftUI Web View

Daily Coding Tip 045

There still isn’t a web view in SwiftUI, but we can make a live HTML preview using WebKit.

This requires us to combine a WKWebView and a Binding to the HTML string we want to preview. When the HTML string changes, we simply load it into the web view, refreshing the content that will be displayed.

We’re going to keep it simple and display the live preview above a TextEditor.

This gives us a multiline text area that will expand and become scrollable as we add our HTML.

What if we want to add CSS and JavaScript separately?

I’m working on a more complicated version that allows you to add those too, but it’s made the app so much more complicated that I thought it better to share the basic version first.

Get more Daily Coding Tips in your inbox!