3

I have the following code:

struct TestListView: View {
    
    var body: some View {
        
        Text("the list view")
        
        VStack {
            List {
                ForEach(0..<10) { n in
                    CellView(number: n)
                }
            }
        }
        
    }
    
}


struct CellView:View {
    
    let number:Int
    
    var body: some View {

        /// DOES NOT WORK:
        GeometryReader { geo in
            ZStack {
                Rectangle().fill(.brown)
                Text("Number: \(number)")
            }
            .frame(width: geo.size.width, height: geo.size.width * CGFloat.random(in: 0.5...1)  )
        }
        
        /// WORKS:
//            ZStack {
//                Rectangle().fill(.brown)
//                Text("Number: \(number)")
//            }
//            .frame(width: 200, height: 200 * CGFloat.random(in: 0.5...1)  )
        
    }
    
}

It renders this:

enter image description here

If I change the CellView to this:

struct CellView:View {
    
    let number:Int
    
    var body: some View {

        /// DOES NOT WORK:
//        GeometryReader { geo in
//            ZStack {
//                Rectangle().fill(.brown)
//                Text("Number: \(number)")
//            }
//            .frame(width: geo.size.width, height: geo.size.width * CGFloat.random(in: 0.5...1)  )
//        }
        
        /// WORKS:
            ZStack {
                Rectangle().fill(.brown)
                Text("Number: \(number)")
            }
            .frame(width: 200, height: 200 * CGFloat.random(in: 0.5...1)  )
        
    }
    
}

Then the cell is able lot set its own height:

enter image description here

Why is using GeometryReader breaking things? How can I allow the cell to use geometry reader size information to then set its height in this case according to custom cell logic?

zumzum
  • 17,984
  • 26
  • 111
  • 172
  • GeometryReader always takes up all available space, kind of like a `Spacer()`. What are you using it for? – aheze Dec 30 '21 at 18:02
  • I have some logic I need to use that needs to let the cell set its height based on a few factors, one of them being the width the cell has available. – zumzum Dec 30 '21 at 18:04
  • 2
    You'll need to put it in a `.background` or something then. See https://stackoverflow.com/questions/66793834/size-of-view-in-swiftui/66822461#66822461 – aheze Dec 30 '21 at 18:06
  • This can be helpful https://stackoverflow.com/a/62482773/12299030. – Asperi Dec 31 '21 at 06:41

0 Answers0