I have several views in a VStack/ScrollView using SwiftUI, The text elements I want to be leading (not centered in the view) but the Image I want centered on the Y axis. I’ve tried using center alignment in the frame but not the image still aligned leading. I tried making the VStack not aligned to leading with the Text aligned leading in the frame, but it just aligned center.
What is the correct way to handle this?
var body: some View {
GeometryReader { geo in
VStack {
ScrollView(.vertical, showsIndicators: false) {
VStack(alignment: .) {
Text(title: viewData.title, font: .bold, size: 22)
.padding(.top, 27)
Text(title: viewData.body1, font: .regular, size: 16)
.padding(.top, 4)
.frame(alignment: .center)
Image(viewData.headerImageName ?? "")
.padding(.top, 80)
.frame(width: 88, height: 91, alignment: .center)
}
}
.padding(.horizontal, 16)
Spacer()
Button(action: {
self.navigateToNext()
}, label: {
Text(title: viewData.buttonTitle, font: .regular, size: 16)
.foregroundColor(.white)
})
.frame(width: geo.size.width - 32, height: 48, alignment: .center)
.background(Color(UIColor.Green))
.cornerRadius(8)
}
}
}
2
Answers
There are a few ways to get the alignment you’re looking for. I’ve provided a few simplified examples below:
Option 1
Option 2
Option 3
Additionally, the GeometryReader is not required on the overall frame.
This line:
Can be replaced by:
here is an approach (and IMHO you don’t need geometryReader):