SwiftUI列表中所有行的高度均相同

时间:2020-02-10 07:07:23

标签: ios swift swiftui

我正在尝试构建一个List,其中所有行都具有相同的高度

struct ContentView: View {

    @State var content = ["row1", "row2\nrow2\nrow2", "row3"]

    var body: some View {
        List {
            ForEach(0..<content.count, id: \.self) { index in
                Text(self.content[index])
            }
        }
    }
}

第1行和第3行应与第2行具有相同的高度 enter image description here

1 个答案:

答案 0 :(得分:3)

这是一种解决方法。 我已经使用geometryReader来计算内容的高度。一旦获得了内容的最大高度,就可以借助首选项来更新单元格。

struct TestView: View {
@State var content = ["row1", "row2\nrow2\nrow2", "row3"]
@State var rowHeight: CGFloat = 0

var body: some View {
  List {
      ForEach(0..<content.count, id: \.self) { index in
        Text(self.content[index])
            .frame(minHeight: self.rowHeight)  // set height as max height
            .background(
                GeometryReader{ (proxy) in
                    Color.clear.preference(key: SizePreferenceKey.self, value: proxy.size)  
            })
            .onPreferenceChange(SizePreferenceKey.self) { (preferences) in
                let currentSize: CGSize = preferences
                if (currentSize.height > self.rowHeight) {
                    self.rowHeight = currentSize.height     //As height get change upto max height , put value in self.rowHeight
                }
            }
      }
  }
}
}

struct SizePreferenceKey: PreferenceKey {
    typealias Value = CGSize
    static var defaultValue: Value = .zero

    static func reduce(value: inout Value, nextValue: () -> Value) {
        nextValue()
    }
}

output