SwiftUI ScrollView inside list has terrible performance implications
Asked Answered
F

2

6

I have a really simple SwiftUI view that is listing a bunch of Texts:

extension String: Identifiable {
  public var id: String { return self }
}

struct ContentView: View {
  var items: [String] = (0..<1000).map { $0.description }
  var body: some View {
    List(items) { str in
      HStack {
        Text(str)
      }
    }
  }
}

This code seems to work fine and gives me smooth scroll performance.

If I change this so that the HStack is inside of a horizontally scrolling ScrollView:

var body: some View {
  List(items) { str in
    ScrollView(.horizontal) {
      HStack {
        Text(str)
      }
    }
  }
}

There is an enormous performance hit and memory appears to grow unbounded as I scroll up and down through the list. There aren’t any leaks in the memory debugger.

I’m wondering if anyone knows why the performance hit is so massive and if there’s any way around it.

Update:

The HStack and Text appear to be irrelevant to the issue, even a Spacer inside the scrollView will trigger the issue.

List(items) { _ in
  ScrollView(.horizontal) {
    Spacer()
  }
}
Fugger answered 25/9, 2019 at 13:46 Comment(0)
C
2

It seems like there might be a memory leak issue with at least List, ScrollView, Form, and NavigationView (see this question). The author of that question filed feedback with Apple (FB7318839). I would encourage you to do so as well, and hopefully it's just a bug that gets fixed soon.

Cf answered 25/9, 2019 at 14:10 Comment(1)
Filed as FB7324303Fugger
C
0

If you need the main ScrollView or List to display another horizontal list or lists there is very good trick to make the performance perfect, just wrap each of your horizontal collections with Section like this:

Section {
    //horizontal collection here
}
Centrifugate answered 26/3 at 11:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.