SwiftUI does not allow for a child of an HStack
or a VStack
to be centered. This package aims to provide a solution to this problem.
- Add the
CenteredStack
package to your Xcode project. - Import
CenteredStack
to your file.
import SwiftUI
import CenteredStack // Here
struct ContentView: View {
...
}
- Use it like a regular
HStack
orVStack
.
struct ContentView: View {
var body: some View {
CenteredVStack {
// Add content here
}
}
}
- Add the
centered()
modifier to the child you want to center.
struct ContentView: View {
var body: some View {
CenteredVStack {
Text("Not centered")
Text("Centered")
.centered() // Here
}
}
}
You cannot use a Spacer
and the .centered()
modifier in the same stack.
If you need to use a Spacer
, use a ZStack
.
Here is an example:
struct ContentView: View {
var body: some View {
ZStack {
HStack { // Separate HStack that contains the Spacer
Button("Back") {}
Spacer()
Button("Add") {}
}
CenteredHStack {
Image(systemName: "person.fill")
Text("John Smith")
.centered()
}
}
.padding(20)
.background(.blue.opacity(0.1))
.clipShape(.rect(cornerRadius: 8))
}
}