Hello, SwiftUI!
This episode, we will take a look at SwiftUI, a brand new framework just released at WWDC 2019. We will create just a basic view of text and an image to show off how it works.
Getting started with SwiftUI
We will start with a basic SwiftUIView
. The only requirement is to return something from thebody
property. We will return a text element here. You'll notice that the text elemtn shrink wraps its content, and the parent view places it at the center of the screen in its container. We can tweak this view by usingmodifiers. These alter the way views are rendered. Note that order matters here, so you'll get a different result if you add padding before the background color or after.
structContentView:View{varbody:someView{Text("Hello World").font(.largeTitle).fontWeight(.black).foregroundColor(.white).padding().background(Color.red)}}
Working with View Container
SwiftUI defines a few containers which can be used to arrange multiple views. We will use theVStack
or vertical stack. The elements of this container are centered horizontally by default. We can change the alignment by setting it to.leading
or.trailing
.
structContentView:View{varbody:someView{VStack(alignment:.center){Text("Hello World").font(.largeTitle).fontWeight(.black).foregroundColor(.white).padding().background(Color.red)Text("this is Swift UI, isn't it neat?").font(.title).padding().background(Color.green).foregroundColor(.white)}}}
Swift also providesHStack
or horizontal stack container where elements are placed horizontally and are centered vertically by default. We can set the alignment of this container to.top
,.bottom
or.center
.
Working with Images
Now we will work with anImage
. To create an image we are using icons provided bySF symbols. To have views lay on top of one another we can use aZStack
, which is another type of view container provided by SwiftUI.
structCircleStar:View{varbody:someView{ZStack{Image(systemName:"circle").resizable().aspectRatio(1,contentMode:.fit).frame(width:180).foregroundColor(.blue)Image(systemName:"star.fill").resizable().aspectRatio(1,contentMode:.fit).frame(width:200).foregroundColor(.blue)}}}
To render our customCircleStar
view into our mainContentView
we can simply instantiate it:
Displaying Preview across the screen in Catalina
Xcode 11 on macOS Catalina provides a live preview section which runs on the screen simultaneously. It also provides preview mode which defines the frames of the elements.
#if DEBUGstructCircleStar_Previews:PreviewProvider{staticvarpreviews:someView{CircleStar()}}#endif
We can use this to customize the preview behavior (changing devices, frames, etc) or by providing test data to see how everything renders.
This episode uses Xcode 11.0-beta1, Swift 5.1.