Evan C
Evan C

Reputation: 77

Using SwiftUI in Xcode 11 playground

I know how to use SwiftUI in Xcode 11 in a regular app project, but I was wondering if there was a way to use it in playgrounds as well, even if I couldn't use the live editor?

Upvotes: 2

Views: 2062

Answers (2)

Andre Carrera
Andre Carrera

Reputation: 2696

Sure, it's pretty easy:

import PlaygroundSupport

PlaygroundPage.current.liveView = UIHostingController(rootView: PlaygroundRootView())

public struct PlaygroundRootView: View {
    public init() {}

    public var body: some View {
        Text("Hello World!")
    }
}

see more here: https://github.com/attoPascal/SwiftUI-Tutorial-Playground

Upvotes: 6

Anton
Anton

Reputation: 736

On macOS Mojave besides using PlaygroundPage.current.liveView you can draw your SwiftUI view into an image. That way you can have multiple "live views" in your playground.

Check out this article: https://ericasadun.com/2019/06/20/swiftui-render-your-mojave-swiftui-views-on-the-fly/

The sample code is hosted here https://gist.github.com/erica/fb5005f625207e108836175ff201d8f2

The renderedImage utility code (copyright by Erica Sadun!)

import PlaygroundSupport
import SwiftUI
extension UIView {
  var renderedImage: UIImage {
    let image = UIGraphicsImageRenderer(size: self.bounds.size).image { context in
      UIColor.lightGray.set(); UIRectFill(bounds)
      context.cgContext.setAlpha(0.75)
      self.layer.render(in: context.cgContext)
    }
    return image
  }
}
extension View {
  var renderedImage: UIImage {
    let window = UIWindow(frame: CGRect(origin: .zero, size: CGSize(width: 320, height: 160)))
    let hosting = UIHostingController(rootView: self)
    hosting.view.frame = window.frame
    window.rootViewController = hosting
    window.makeKey()
    return hosting.view.renderedImage
  }
}

Upvotes: 1

Related Questions