4

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 enter image description here

8
  • Have you tried to set .frame for Text(self.content[index]) ? Commented Feb 10, 2020 at 7:24
  • @KeyurTailor I do not know the frame, the height should be according to the biggest height in the list Commented Feb 10, 2020 at 7:26
  • @KeshuR. Not really, .defaultMinListRowHeight can be used to set a minim height, but I do not know the height for my rows Commented Feb 10, 2020 at 7:32
  • You need to calculate the maximum height for the longest string in your content and then use frame for Text with that calculated height. Commented Feb 10, 2020 at 7:38
  • @Kamran I used Text view for this example, my real rows are much complex than that, a couple of Text views arranged with HStack and VStack, so this would not work Commented Feb 10, 2020 at 7:49

1 Answer 1

9

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()
    }
}

output

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.