SwiftUI Fundamentals

Feb 28 2023 · Swift 5.7, macOS Venture 13.1, Xcode 14.2

Part 1: SwiftUI Views

07. Layout with Stacks

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 06. Challenge: State & Binding Next episode: 08. Repeat Views with ForEach & Lists

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

One of the most powerful SwiftUI components is the Stack.

VStack(alignment: .leading, spacing: 20.0) {
HStack {
      
}
Button { print("Play!") }
  label: { 
  
  }
Label("Play", systemImage: "play.fill")
Spacer()
Label(...)
Spacer()
HStack {
...
}
.padding(.vertical)
.background(Color.gray.opacity(0.15))
.cornerRadius(12)
struct ButtonLabel: View {
  let title: String
  let systemImage: String
  
  var body: some View {
    ...
    Label(title, systemImage: systemImage)
label: { ButtonLabel(title: "Play", systemImage: "play.fill") }
Button { print("Shuffle!") }
  label: { ButtonLabel(title: "Shuffle", systemImage: "shuffle") }

ZStacks

The third kind of Stack is called a ZStack. It stacks views depth-wise, like this big orange square with the text and play symbol in it.

struct Thumbnail: View {
  var body: some View {
Thumbnail()
  .padding()
  .previewLayout(.fixed(width: 250, height: 250))
ZStack(alignment: Alignment(horizontal: .center, vertical: .center)) {

}
Alignment(horizontal: .leading, vertical: .top)
RoundedRectangle(cornerRadius: 12)
  .foregroundColor(.orange)
  .aspectRatio(1, contentMode: .fit)
  .shadow(radius: 10)
Image(systemName: "play.fill")
  .resizable()
  .frame(width: 50, height: 50)
  .foregroundColor(.white)
  .opacity(0.4)
VStack(alignment: .leading) {
  Text("Meow!")
    .font(.largeTitle)
    .fontWeight(.black)
  Text("Mix")
    .font(.largeTitle)
  
  Spacer()
}
.foregroundColor(.white)
.padding()

Put it together!

Now you just need to put it all together.

HStack(alignment: .bottom, spacing: 20) {
  Thumbnail()
}
.padding()
.frame(minHeight: 150, maxHeight: 250)