Dunfey · Hotel WWDC as data, est. 1983
Front desk everything
Years
Topics

2020 Swift

WWDC20 · 14 min · Swift

Build a SwiftUI view in Swift Playgrounds

Easily prototype and play around with SwiftUI views when you use them with Swift Playgrounds. We’ll show you how to build a SwiftUI view in a Xcode-compatible playground, and explore tools to help you easily edit and preview your code. For more on Swift Playgrounds, check out our interactive challenge, “Swan’s Quest”, and learn to build your own by watching “Create Swift Playgrounds Content for iPad and Mac”.

Watch at developer.apple.com ↗

Transcript all transcripts

Code shown on screen · 22 snippets

Set up for SwiftUI swift · at 2:30 ↗
import SwiftUI
import PlaygroundSupport
Create a simple SwiftUI view swift · at 2:46 ↗
struct ProgressView: View {
  
  var body: some View {
    Text("Hello, world!")
  }
  
}
Show a SwiftUI live view swift · at 3:12 ↗
PlaygroundPage.current.setLiveView(ProgressView())
Create a blue circle swift · at 4:01 ↗
Circle()
	.stroke(lineWidth: 25)
	.foregroundColor(.blue)
Add some padding swift · at 5:06 ↗
ProgressView().padding(150)
Create an empty ZStack swift · at 5:30 ↗
ZStack { }
Add a text view swift · at 5:51 ↗
Text("25%")
Make a struct public swift · at 9:24 ↗
public struct ProgressView: View {
Make a view's body property public swift · at 9:38 ↗
public var body: some View {
Make a view's initializer public swift · at 9:45 ↗
public init(_ progress: Double = 0.3) {
Create another SwiftUI view swift · at 10:12 ↗
struct Preview: View {
 
  var body: some View {
    // ...
  }
  
}
Create a VStack of progress views swift · at 10:21 ↗
VStack(spacing: 30) {
  ProgressView()
  ProgressView()
}
Add padding to a view swift · at 10:44 ↗
.padding(100)
Add a system background color to a view swift · at 10:51 ↗
.background(Color(UIColor.secondarySystemBackground))
Initialize the Preview view swift · at 11:19 ↗
Preview()
Use an environment modifier to preview dark mode swift · at 11:35 ↗
.environment(\.colorScheme, .dark)
Create a state variable for tracking progress swift · at 12:12 ↗
@State var progress = 0.25
Pass the progress to the ProgressView initializer swift · at 12:18 ↗
ProgressView(progress)
Create a method for incrementing progress swift · at 12:32 ↗
func increment() {
  self.progress += 0.25
}
Add animation to the increment method swift · at 12:40 ↗
func increment() {
  withAnimation {
    self.progress += 0.25
  }
}
Create a button swift · at 12:52 ↗
Button(action: increment)
Add a text label to a button swift · at 13:01 ↗
Button(action: increment) {
  Text("Increment Progress")
}