简体   繁体   English

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

[英]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())搜索栏冻结了列表,但我使用id(UUID())修复了它

It created another problem, in which when user taps on a row, scroll jumps to top .它产生了另一个问题,当用户点击一行时,滚动跳转到 top Sometimes, when selecting few rows it crashes with this error: precondition failure: attribute failed to set an initial value: 96 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.完整的项目在GitLab上可用,还有其他截屏视频和文件,如选择视图、搜索栏和视图模型。

截屏显示跳跃滚动视图

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.使用 SearchBar 时,键盘和列表冻结。
  2. Use.id(UUID()) to fix freezes, but it adds another misbehavior: list scrolls to top every time selecting row.使用.id(UUID()) 修复冻结,但它增加了另一个错误行为:每次选择行时列表都会滚动到顶部。 And it used to crash.它曾经崩溃过。

I ended up using UITableView with UIViewRepresentable.我最终使用了带有 UIViewRepresentable 的 UITableView。 When I replaced List with UITableView, I added property @Binding var offset: CGFloat and updated it every time row is being selected:当我用 UITableView 替换 List 时,我添加了属性@Binding var offset: CGFloat并在每次选择行时更新它:

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.感谢您尝试提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM