Skip to content

Instantly share code, notes, and snippets.

@ytyubox
Last active August 21, 2022 08:25
Show Gist options
  • Save ytyubox/f064959e78ba46ddff7566a64ed98005 to your computer and use it in GitHub Desktop.
Save ytyubox/f064959e78ba46ddff7566a64ed98005 to your computer and use it in GitHub Desktop.

Flex Layout Justify Content with SwiftUI

Key take aways

  • Spacer
  • Layout

CleanShot 2022-08-21 at 15 09 51@2x

//
// ContentView.swift
// Layout
//
// Created by Yu Yu on 2022/8/21.
//
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(spacing: 0) {
Text("Flex Layout Justify Content").font(.title2).padding()
VStack(spacing: 0) {
Text("Start")
HStack(spacing: 10) {
box1
box2
box3
Spacer()
}
.padding(.vertical, 5)
.background(color)
.padding(.horizontal)
}
VStack(spacing: 0) {
Text("End")
HStack(spacing: 10) {
Spacer()
box1
box2
box3
}
.padding(.vertical, 5)
.background(color)
.padding(.horizontal)
}
VStack(spacing: 0) {
Text("Center")
HStack(spacing: 10) {
box1
box2
box3
}
.frame(maxWidth: .infinity)
.padding(.vertical, 5)
.background(color)
.padding(.horizontal)
}
VStack(spacing: 0) {
Text("Space Between")
HStack(spacing: 10) {
box1
Spacer()
box2
Spacer()
box3
}
.padding(.vertical, 5)
.background(color)
.padding(.horizontal)
}
VStack(spacing: 0) {
Text("Space Around ")
HStack {
Spacer()
box1
Spacer()
Spacer()
box2
Spacer()
Spacer()
box3
Spacer()
}
.frame(height: 30)
.padding(.vertical, 5)
.background(color)
.padding(.horizontal)
}
VStack(spacing: 0) {
Text("Space Evenly")
HStack(spacing: 10) {
Spacer()
box1
Spacer()
box2
Spacer()
box3
Spacer()
}
.padding(.vertical, 5)
.background(color)
.padding(.horizontal)
}
}
}
var color: Color { Color(white: 0.4) }
@ViewBuilder var box1: some View { box(2) }
@ViewBuilder var box2: some View { box(5) }
@ViewBuilder var box3: some View { box(10) }
@ViewBuilder
func box(_ int: Int) -> some View {
Text(String(repeating: "*", count: int))
.font(.body)
.padding(5)
.lineLimit(1)
.background(Color.orange)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment