SwiftUI:当有 `.id(UUID())` 时,列表会在选择一行时向上滚动

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

我有一个包含选择行和搜索栏的列表。 搜索栏冻结了列表,但我使用 id(UUID())

解决了这个问题

它产生了另一个问题,当用户点击一行时,滚动跳到顶部。 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 : [=10=].title.lowercased().contains(searchText.lowercased()) })
        , selection: $selected) { model in
            MultipleSelectionRow(selectedItems: self.$selected, model: model)
        }
        .id(UUID()) /// This line causes strange behaviour.
    }
  }
}

完整项目可在 GitLab 上获得,还有其他截屏视频和文件,例如选择视图、搜索栏和 viewModel。

已解决:

最初有两种使用列表的方法,但每种方法都有自己的错误。

  1. 使用 SearchBar 时,键盘和列表冻结。
  2. 使用 .id(UUID()) 修复冻结,但它增加了另一个错误行为:每次选择行时列表都会滚动到顶部。它曾经崩溃。

我最终将 UITableView 与 UIViewRepresentable 结合使用。当我用 UITableView 替换 List 时,我添加了 属性 @Binding var offset: CGFloat 并在每次选择行时更新它:

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

不好意思问的不清楚,当时脑子里很清楚。感谢您的帮助。