jam*_*mes 7 xcode ios swift swiftui
我是 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()
}
}
}
Run Code Online (Sandbox Code Playgroud)
但正如您所看到的,这只将元素向左对齐 - 我也不知道可能需要显示的字符数。我还希望保持它们之间的间距与上面相同。
任何帮助将不胜感激!
谢谢。
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()
}
}
}
Run Code Online (Sandbox Code Playgroud)
改成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()
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如评论中提到的,如果您设置一个,maximum它们将居中/对齐到该最大值
| 归档时间: |
|
| 查看次数: |
5269 次 |
| 最近记录: |