我是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()
}
}
}但正如您所看到的,这只会使元素向左对齐-我也不知道可能需要显示的字符数。我也希望他们之间的间距保持不变。
任何帮助都将不胜感激!
谢谢。
发布于 2021-07-17 22:50:58
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,带3行,最多40行

LazyVGrid w/ 5列,最多40列

https://stackoverflow.com/questions/68385250
复制相似问题