我想根据我需要的条件设计水平网格,当数据来自API时,满足“标题”时,那么应该只有整行中的一个单元格,否则为4个单元格。
ScrollView{
LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())], spacing: 2) {
ForEach(bleGroupMeta.fetchedData) { index in
if index.desc != "HEADING" {
TextField("", text: Binding(
get: { userMeasurements[index.id].stringValue },
set: { newValue in
userMeasurements[index.id] = JSON(newValue)
let measurement = Measurement(measurement: index.id, value: newValue)
print(measurement)
if !modifiedMeasurements.contains(measurement) {
modifiedMeasurements.append(measurement)
}
}
) , prompt: Text(index.desc)
.font(Font.custom("Agency FB", size: 16))
.foregroundColor(Constants.White.opacity(0.8)))
.padding(.leading)
.keyboardType(.decimalPad)
.font(Font.custom("Agency FB", size: 16))
.foregroundColor(Constants.White.opacity(0.8))
.background(Color.clear)
.frame(height: 40)
.frame(maxWidth: .infinity)
.cornerRadius(4)
.overlay(
RoundedRectangle(cornerRadius: 4)
.inset(by: 0.5)
.stroke(Color(red: 0.26, green: 0.27, blue: 0.3), lineWidth: 1)
)
} else {
// Add the design for the heading
VStack {
HStack(spacing: 20){
Rectangle().fill(Color.gray).frame(height: 1)
// Spacer()
Text("Heading").font(Font.custom("Agency FB", size: 16)).foregroundColor(Constants.Orange)
// Spacer()
Rectangle().fill(Color.gray).background(Color.gray).frame(height: 1)
}
}.frame(maxWidth: .infinity)
}
}.padding()
}
}
您可以调用gridSwitch()函数并使用gridColumn设置gridLayout。
@State private var gridLayout: [GridItem] = [GridItem(.flexible())]
@State private var gridColumn: Int = 1
func gridSwitch(isHeadingType: Bool) {
gridColumn = isHeadingType ? 1 : 4
gridLayout = Array(repeating: .init(.flexible()), count: gridColumn)
gridColumn = gridLayout.count
}
ScrollView(.vertical, showsIndicators: false) {
LazyVGrid(columns: gridLayout, alignment: .center, spacing: 10) {
ForEach(bleGroupMeta.fetchedData) { item in
NavigationLink(destination: DetailView(gridItem: item)) {
DetailItemView(gridItem: item)
}
}//: Loop
}//: Grid
}