我正在尝试使用具有列标题和一些行的表的ZStack显示自定义布局,但是我得到的布局与我在正文中指定的顺序相反。这是代码:
import SwiftUI
struct Test: View {
var columns : [String] = ["Column 1","Column 2"]
var cells : [[String]] = [
["(1,1)","(1,2)"],
["(2,1)","(2,2)"],
["(3,1)","(3,2)"],
]
var body: some View {
ZStack(alignment: .topLeading) {
ForEach(0..<self.columns.count, id: \.self) { column in
self.viewForCell(self.columns[column], row: 0, column: column)
}
ForEach(0..<self.cells.count, id: \.self) { row in
ForEach(0..<self.cells[row].count, id: \.self ) { column in
self.viewForCell(self.cells[row][column], row: 1+row, column: column)
}
}
}
}
func viewForCell(_ string: String, row: Int, column: Int) -> some View {
Text(string)
.alignmentGuide(.leading, computeValue: { _ in CGFloat(96 * column) })
.alignmentGuide(.top, computeValue: { _ in CGFloat(24 * row) })
}
}
struct Test_Previews: PreviewProvider {
static var previews: some View {
Test()
}
}
我想要的是:
"Column 1" "Column 2"
"(1,1)" "(1,2)"
"(2,1)" "(2,2)"
"(3,1)" "(3,2)"
似乎水平和垂直对齐方式都被翻转了。
答案 0 :(得分:0)
import SwiftUI
struct Test: View {
var columns : [String] = ["Column 1","Column 2"]
var cells : [[String]] = [
["(1,1)","(1,2)"],
["(2,1)","(2,2)"],
["(3,1)","(3,2)"],
]
var body: some View {
ZStack(alignment: .topLeading) {
ForEach(0..<self.columns.count, id: \.self) { column in
self.viewForCell(self.columns[column], row: 0, column: column)
}
ForEach(0..<self.cells.count, id: \.self) { row in
ForEach(0..<self.cells[row].count, id: \.self ) { column in
self.viewForCell(self.cells[row][column], row: 1+row, column: column)
}
}
}
}
func viewForCell(_ string: String, row: Int, column: Int) -> some View {
Text(string)
.alignmentGuide(.leading, computeValue: { _ in CGFloat(96 * ( self.columns.count - column ) ) })
.alignmentGuide(.top, computeValue: { _ in CGFloat(24 * ( self.cells.count - row ) )})
}
}
struct Test_Previews: PreviewProvider {
static var previews: some View {
Test()
}
}
@andrewz问题出在单元格的alignmentGuide的前导值和顶部 上面的代码将按您期望的方式工作:)