在 Xcode 11 playground 中使用 SwiftUI

Using SwiftUI in Xcode 11 playground

我知道如何在 Xcode 11 的常规应用程序项目中使用 SwiftUI,但我想知道是否有办法在 playgrounds 中也使用它,即使我不能使用 live编辑?

当然,这很简单:

import PlaygroundSupport

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

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

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

在此处查看更多信息: https://github.com/attoPascal/SwiftUI-Tutorial-Playground

在 macOS Mojave 上,除了使用 PlaygroundPage.current.liveView 之外,您还可以将 SwiftUI 视图绘制到图像中。这样你就可以在 playground 中拥有多个 "live views"。

查看这篇文章:https://ericasadun.com/2019/06/20/swiftui-render-your-mojave-swiftui-views-on-the-fly/

示例代码托管在这里 https://gist.github.com/erica/fb5005f625207e108836175ff201d8f2

renderedImage 实用代码(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
  }
}