我是 SwiftUI 的新手,正在尝试将 LazyVGrid
中的元素居中看法。
这是我目前所拥有的:
使用:
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()
}
}
}
但是正如您所看到的,这只会将元素向左对齐 - 我也不知道可能需要显示的字符数。我还希望保持它们之间的间距与上述相同。任何帮助将不胜感激!
谢谢。
最佳答案
2个选项
struct CenteredLVSView: View {
@State var letters: [String] = ["A", "B", "C", "D", "E","A", "B", "C", "D", "E","A", "B", "C", "D", "E"]
//Specify column count and it will justify/center by width
@State var columnCount: Int = 5
var body: some View {
ZStack {
Color(red: 75/255, green: 0, blue: 130/255).ignoresSafeArea()
LazyVGrid(columns: Array(repeating: GridItem(.flexible(minimum: 30
//If you set max it will center on width if smaller than max, uncomment below
//, maximum: 40
)), count: columnCount), spacing: 10){
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()
}
}
}
更改为
LazyHGrid
struct CenteredLVSView: View {
@State var letters: [String] = ["A", "B", "C", "D", "E","A", "B", "C", "D", "E","A", "B", "C", "D", "E"]
//Specify row count and it will justify/center height
@State var rowCount: Int = 5
var body: some View {
ZStack {
Color(red: 75/255, green: 0, blue: 130/255).ignoresSafeArea()
LazyHGrid(rows: Array(repeating: GridItem(.flexible(minimum: 30
//If you set max it will center if smaller than max, height uncomment below
//, maximum: 40
)), count: rowCount), spacing: 10){
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()
}
}
}
正如评论中提到的,如果您设置了
maximum
他们将居中/合理化到那个最大值LazyHGrid w/3 行,最多 40
LazyVGrid 有 5 列,最多 40
关于ios - LazyVGrid 中的 SwiftUI 中心项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68385250/