Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Force List Row to adjust height to content

I'm having some issues with a List that won't change the row's height. I split it off into an easy example.

This is the entire demo code:

struct ContentView: View {
  let items = ["item 1", "item 2", "item 3"]
  @State var error: [String: String] = []
  
  var body: some View {
    List {
      ForEach(self.items, id: \.self) { item in
        VStack {
          Text(item)
            .padding()
          if let e = error[item] {
            Text(e)
          }
        }
        .swipeActions(edge: .leading, allowsFullSwipe: true) {
          Button(action: {
            self.error[item] = "ERROR!"
          }) {
            Image(systemName: "square.and.arrow.up")
          }.background(Color.blue)
        }
      }
    }
  }
}

I want to show an error message below the regular item, once the user swipes the cell. Unfortunately what happens now is this:

issue

What I want it to look like is this (for this I added an element to the 'error' dictionary in the code):

fix

It seems to me like a problem many people would face, but I haven't been able to find much information about this issue. I've tried some things (for example the '.fixedSize' modifier), but nothing I have tried has worked.

like image 274
Adam Avatar asked Oct 14 '25 22:10

Adam


1 Answers

List caches created rows, so we need to let it known that specific row should be rebuilt from scratch. The possible solution is to use .id dependent on same condition as optional error text.

Tested with Xcode 13.2 / iOS 15.2

enter image description here

Here is modified part of code (some extra added for demo):

.swipeActions(edge: .leading, allowsFullSwipe: true) {
  Button(action: {
    if nil == self.error[item] {
        self.error[item] = "ERROR!"
        } else {
            self.error[item] = nil
        }
  }) {
    Image(systemName: "square.and.arrow.up")
  }.background(Color.blue)
}
.id(item + (self.error[item] ?? ""))   // << here !!
like image 124
Asperi Avatar answered Oct 17 '25 13:10

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!