SwiftUI Example: How to make a “U.S. Traffic Light” in Code
Now that we’re getting to the point where Xcode 11 and Swift UI are due for official release in a few weeks, I have been experimenting with the language and will be sharing my findings in this SwiftUI limited series.
Thank you for reading this post, don't forget to subscribe!
One of the unique features about the language is that one can finally draw shapes without having to know complex mathematical formulas or have a mind of a rocket scientist.
My first example project may seem simple – to make three different colored circles on the screen, put text in the middle of them, and have it inside of a basic (non-row) NavigationView.
Here are the steps (and the code) to accomplish the above:
- Open Xcode.
- Select FILE > NEW PROJECT. Name it what ever you’d like.
- Make sure SWIFT UI is checked off, then click NEXT.
Now that the SwiftUI screen is up, delete the Text line, and replace it with the following code:
import SwiftUI
struct ContentView : View {
var body: some View {
NavigationView {
VStack {
Circle()
.foregroundColor(Color.red)
.frame(width: 200, height: 200, alignment: .center)
Circle()
.foregroundColor(Color.yellow)
.frame(width: 200, height:200, alignment: .center)
Circle()
.foregroundColor(Color.green)
.frame(width: 200, height: 200, alignment: .center)
ZStack {
Text(“Stop”)
.fontWeight(.bold)
.font(.largeTitle)
.foregroundColor(Color.white)
.position(x: 210, y: -535)
Text(“Caution”)
.fontWeight(.bold)
.font(.largeTitle)
.foregroundColor(Color.black)
.position(x: 205, y: -330)
Text(“Go”)
.fontWeight(.bold)
.font(.largeTitle)
.foregroundColor(Color.black)
.position(x: 209, y: -120)
Text(“By: Dan M. Uff”)
.fontWeight(.bold)
.font(.largeTitle)
.foregroundColor(.white)
.background(Color.black)
.padding(20)
}.navigationBarTitle(Text(“Color Dots Test”))
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
Group {
ContentView()
.previewDevice(“iPhone-XR”)
}
}
}
#endif
}
About Post Author
Discover more from CompuScoop.com
Subscribe to get the latest posts sent to your email.