Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: List scrolls up on selection of a row when there's `.id(UUID())`

I have a list with selecting rows and a search bar. Search bar freezes up the list, but I fixed that using id(UUID())

It created another problem, in which when user taps on a row, scroll jumps to top. Sometimes, when selecting few rows it crashes with this error: precondition failure: attribute failed to set an initial value: 96

struct ContentView: View {

@ObservedObject var viewModel = ViewModel()
@State private var searchText: String = ""
@State private var selected = Set<Model>()

var body: some View {
    VStack {
        SearchBar(text: $searchText, placeholder: "Search")
        List(
            viewModel.strings.filter({ searchText.isEmpty ? true : $0.title.lowercased().contains(searchText.lowercased()) })
        , selection: $selected) { model in
            MultipleSelectionRow(selectedItems: self.$selected, model: model)
        }
        .id(UUID()) /// This line causes strange behaviour.
    }
  }
}

The full project is available on GitLab with other screencasts and files like selection view, search bar and viewModel.

Screencast shows jumping scroll view

like image 494
lazydev Avatar asked Dec 01 '25 14:12

lazydev


1 Answers

SOLVED:

There're initially two ways to use list, but each one had it's own bugs.

  1. When using SearchBar, keyboard and list was freezing.
  2. Use .id(UUID()) to fix freezes, but it adds another misbehavior: list scrolls to top every time selecting row. And it used to crash.

I ended up using UITableView with UIViewRepresentable. When I replaced List with UITableView, I added property @Binding var offset: CGFloat and updated it every time row is being selected:

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    offset = tableView.contentOffset.y
    return indexPath 
}

Sorry for unclear question, it was clear in my mind back then. Thank you for trying to help.

like image 133
lazydev Avatar answered Dec 03 '25 04:12

lazydev



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!