【问题标题】:Using SwiftUI in Xcode 11 playground在 Xcode 11 游乐场中使用 SwiftUI
【发布时间】:2019-06-26 02:33:49
【问题描述】:

我知道如何在常规应用项目中使用 Xcode 11 中的 SwiftUI,但我想知道是否有办法在 Playground 中使用它,即使我不能使用实时编辑器?

【问题讨论】:

    标签: swift-playground swiftui xcode11


    【解决方案1】:

    当然,这很容易:

    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

    【讨论】:

      【解决方案2】:

      在 macOS Mojave 上,除了使用 PlaygroundPage.current.liveView 之外,您还可以将 SwiftUI 视图绘制成图像。这样,您就可以在 Playground 中拥有多个“实时视图”。

      查看这篇文章: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
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-12
        • 1970-01-01
        • 2016-01-26
        相关资源
        最近更新 更多