Reputation: 7636
I am trying to build a List
in which all rows have the same height
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])
}
}
}
}
Row1 and row3 should have the same height with row2
Upvotes: 4
Views: 2899
Reputation: 261
Here is a Workaround. I have used geometryReader for calculate content height.Once we get the max height for the content, with the help of preferences update the cell.
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()
}
}
Upvotes: 9