Alignment and spacing help arrange items neatly on the screen. They make the app look clean and easy to use.
0
0
Alignment and spacing in iOS Swift
Introduction
To center a button in the middle of the screen.
To add space between text and images.
To align labels to the left or right for better reading.
To create equal gaps between multiple buttons.
To make sure content looks good on different screen sizes.
Syntax
iOS Swift
VStack(alignment: .leading, spacing: 10) { Text("Hello") Text("World") }
alignment sets how items line up horizontally inside the stack.
spacing sets the space between each item vertically.
Examples
This arranges an icon and text side by side with space between.
iOS Swift
HStack(alignment: .center, spacing: 20) { Image(systemName: "star") Text("Favorite") }
This stacks text vertically aligned to the right with small spacing.
iOS Swift
VStack(alignment: .trailing, spacing: 5) { Text("Right aligned") Text("Text") }
Spacer adds flexible empty space to push views apart.
iOS Swift
Spacer()
Sample App
This example shows a vertical stack with a title and a horizontal stack of menu items spaced apart by spacers. The menu items are evenly spaced across the screen.
iOS Swift
import SwiftUI struct ContentView: View { var body: some View { VStack(alignment: .center, spacing: 20) { Text("Welcome to the app") .font(.title) HStack(spacing: 30) { Text("Home") Spacer() Text("Profile") Spacer() Text("Settings") } .padding() } .padding() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
OutputSuccess
Important Notes
Use Spacer() to add flexible space that grows to fill available room.
Alignment options include .leading, .center, and .trailing for vertical stacks, and .top, .center, and .bottom for horizontal stacks.
Spacing controls the fixed gap between items, but spacers can create flexible gaps.
Summary
Alignment controls how items line up horizontally or vertically.
Spacing sets the fixed distance between items.
Spacers add flexible space to push items apart evenly.