less than 1 minute read

Previewing SwiftUi code using Xcode playgrounds can be done by using settings live view or UIHostingController.

Let us see this by using the following code snippet (SwiftUI View) which displays a button that increments a counter.

import SwiftUI
import PlaygroundSupport

struct CounterView: View {
    @State private var count: Int = 0

    var body: some View {
        VStack {
            Text("Count: \(count)")
            Button("Increment") {
                count += 1
            }
        }
    }
}

UIHostingController

//PlaygroundPage.current.liveView = UIHostingController.init(rootView: CounterView())

Setting Live View

PlaygroundPage.current.setLiveView(CounterView())

Need iOS Help?

I help developers and founders with:

  • New apps — idea to App Store
  • Bug fixes, debugging & rescue
  • App Store rejections
  • Code review & mentoring
See how we can work together →

10+ years iOS • 10+ published apps • 11,000+ students trained

Updated: