Skip to main content

4、Playground中使用SwiftUI

Playground支持UIKit,要使用SwiftUI,只需要将其包裹在UIHostingViewController中即可。

Getting ready

新建一个Playground:SwiftUIPlayground

How to do it…

  1. 导入framework
import PlaygroundSupport
import SwiftUI
  1. 编写View

extension Text {
func customize(_ color: Color) -> some View {
self.font(.system(.title))
.frame(width: 300, height: 150)
.foregroundColor(.white)
.background(color)
.cornerRadius(10)
}
}

struct ContentView: View {
var body: some View {
VStack(spacing: 12) {
Text("SwiftUI")
.customize(.yellow)
Text("in a")
.customize(.blue)
Text("Playground!")
.customize(.red)
}
}
}

  1. 显示
PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView())

Figure_15.15_B17962

How it works…

Playground 支持通过 PlaygroundPageliveView ,渲染一个UIViewController

我们可以通过将Swiftui包裹在UIHostingController中即可。