In SwiftUI, create custom layouts using VStack, HStack, and ZStack.
VStack (Vertical Stack)
- Arranges views vertically.
- Respects view sizes.
VStack {
Text("View 1")
Text("View 2")
Text("View 3")
}
HStack (Horizontal Stack)
- - Arranges views horizontally.
- - Respects view sizes.
HStack {
Text("View 1")
Text("View 2")
Text("View 3")
}
ZStack (Z-Axis Stack)
- Arranges views overlapping each other.
- Later views cover earlier ones.
ZStack {
Rectangle().fill(Color.blue)
Text("Overlay Text")
}
Combining Stacks
- Nest stacks to create complex layouts.
VStack {
HStack {
Text("View 1")
Text("View 2")
}
Text("View 3")
}
}
Custom Layout Modifiers
- Use modifiers to adjust spacing, padding, alignment.
VStack(spacing: 20) {
Text("View 1")
Text("View 2")
}
.padding(.all, 20)
.alignment(.center)
struct ContentView: View {
var body: some View {
ZStack {
Rectangle().fill(Color.blue)
VStack(spacing: 20) {
HStack {
Text("View 1")
Text("View 2")
}
Text("View 3")
}
.padding(.all, 20)
}
}
}
Best Practices
1. Use VStack for vertical lists.
2. Use HStack for horizontal lists.
3. Use ZStack for overlays.
4. Nest stacks for complex layouts.
5. Adjust spacing, padding, and alignment using modifiers.
6. Use Spacer() to manage layout.
No comments:
Post a Comment