I am new to SwiftUI and am trying to center elements inside the LazyVGrid
View.
Here is what I have currently:
Using:
var body: some View {
ZStack {
Color(red: 75/255, green: 0, blue: 130/255).ignoresSafeArea()
VStack {
LazyVGrid(columns: [GridItem(.adaptive(minimum: 30))], alignment: .center, spacing: 10) {
let letters = wordToArray(word: testWord)
ForEach(Array(letters.enumerated()), id: .offset) { letter in
Text(String(letter.element).capitalized)
.foregroundColor(.blue)
.frame(width:30, height: 40)
.background(Color.yellow)
.cornerRadius(5)
}
}
.padding()
}
}
}
But as you can see, this only aligns the elements to the left – I also do not know the number of characters that I may need to display. I would also like the keep the spacing between them the same as above.
Any help would be greatly appreciated!
Thanks.
2
Answers
2 options
Change to
LazyHGrid
And as mentioned in the comments if you set a
maximum
they will be centered/justified to that maxLazyHGrid w/ 3 rows with a maximum of 40
LazyVGrid w/ 5 columns with a maximum of 40
I faced the same issue and couldn’t solve it so I used a ScrollView and foreach to achieve the same way I need it