gpt4 book ai didi

swiftui - 组合 + SwiftUI Form + RunLoop 导致表格 View 呈现不可预测

转载 作者:行者123 更新时间:2023-12-03 16:57:25 25 4
gpt4 key购买 nike

我有一个组合函数,用于搜索项目列表并返回匹配项。它不仅会跟踪向用户显示哪些与搜索词匹配的项目,还会跟踪哪些项目已被用户标记为“已选择”。
该功能运行良好,包括动画,直到我添加 .debounce(for: .seconds(0.2), scheduler: RunLoop.main).receive(on: RunLoop.main)在Combine 出版商链中。此时,渲染结果在View变得莫名其妙——项目标题开始显示为标题 View ,项目重复等。
您可以在随附的 GIF 中看到结果。

GIF 版本正在使用 .receive(on: RunLoop.main) .注意我什至不在这里使用搜索词,尽管它也会导致有趣的结果。还可能值得注意的是,如果 withAnimation { } 出现问题行,一切正常。已移除。
我希望能够使用 debounce因为列表最终可能会很大,我不想在每次击键时过滤整个列表。
在这些情况下,如何让表格 View 正确呈现?
示例代码(有关痛点和代码解释,请参阅内联注释。它应该按编写的方式运行良好,但如果两个相关行中的任何一行都未注释):


import SwiftUI
import Combine
import UIKit

class Completer : ObservableObject {
@Published var items : [Item] = [] {
didSet {
setupPipeline()
}
}
@Published var filteredItems : [Item] = []
@Published var chosenItems: Set<Item> = []
@Published var searchTerm = ""

private var filterCancellable : AnyCancellable?

private func setupPipeline() {
filterCancellable =
Publishers.CombineLatest($searchTerm,$chosenItems) //listen for changes of both the search term and chosen items
.print()
// ** Either of the following lines, if uncommented will cause chaotic rendering of the table **
//.receive(on: RunLoop.main) //<----- HERE --------------------
//.debounce(for: .seconds(0.2), scheduler: RunLoop.main) //<----- HERE --------------------
.map { (term,chosen) -> (filtered: [Item],chosen: Set<Item>) in
if term.isEmpty { //if the term is empty, return everything
return (filtered: self.items, chosen: chosen)
} else { //if the term is not empty, return only items that contain the search term
return (filtered: self.items.filter { $0.name.localizedStandardContains(term) }, chosen: chosen)
}
}
.map { (filtered,chosen) in
(filtered: filtered.filter { !chosen.contains($0) }, chosen: chosen) //don't include any items in the chosen items list
}
.sink { [weak self] (filtered, chosen) in
self?.filteredItems = filtered
}
}

func toggleItemChosen(item: Item) {
withAnimation {
if chosenItems.contains(item) {
chosenItems.remove(item)
} else {
searchTerm = ""
chosenItems.insert(item)
}
}
}
}

struct ContentView: View {
@StateObject var completer = Completer()

var body: some View {
Form {
Section {
TextField("Term", text: $completer.searchTerm)
}
Section {
ForEach(completer.filteredItems) { item in
Button(action: {
completer.toggleItemChosen(item: item)
}) {
Text(item.name)
}.foregroundColor(completer.chosenItems.contains(item) ? .red : .primary)
}
}
if completer.chosenItems.count != 0 {
Section(header: HStack {
Text("Chosen items")
Spacer()
Button(action: {
completer.chosenItems = []
}) {
Text("Clear")
}
}) {
ForEach(Array(completer.chosenItems)) { item in
Button(action: {
completer.toggleItemChosen(item: item)
}) {
Text(item.name)
}
}
}
}
}.onAppear {
completer.items = ["Chris", "Greg", "Ross", "Damian", "George", "Darrell", "Michael"]
.map { Item(name: $0) }
}
}
}

struct Item : Identifiable, Hashable {
var id = UUID()
var name : String
}

最佳答案

处理异步处理的问题...在您的默认情况下,所有操作都是同步执行的 在一(!)内动画块,所以一切正常。但是在第二种情况下(通过在发布者链中引入任何调度程序)一些操作是同步执行的(比如删除)启动动画,但是发布者的操作在动画已经在进行的那一刻是异步的,并且改变模型会破坏正在运行的动画给不可预测的结果。
解决这个问题的可能方法是将不同块的启动和结果操作分开,并使发布者真正异步但在后台处理并在主队列中检索结果。
这是修改后的发布者链。使用 Xcode 12.4/iOS 14.4 测试
注意:您也可以研究在一个动画块中再次包装所有内容的可能性,但已经在 synk 中检索结果后 - 这将需要更改逻辑,因此仅供考虑
enter image description here

private func setupPipeline() {
filterCancellable =
Publishers.CombineLatest($searchTerm,$chosenItems)
.debounce(for: .seconds(0.5), scheduler: DispatchQueue.main) // debounce input
.subscribe(on: DispatchQueue.global(qos: .background)) // prepare for processing in background
.print()
.map { (term,chosen) -> (filtered: [DItem],chosen: Set<DItem>) in
if term.isEmpty { //if the term is empty, return everything
return (filtered: self.items, chosen: chosen)
} else { //if the term is not empty, return only items that contain the search term
return (filtered: self.items.filter { $0.name.localizedStandardContains(term) }, chosen: chosen)
}
}
.map { (filtered,chosen) in
(filtered: filtered.filter { !chosen.contains($0) }, chosen: chosen) //don't include any items in the chosen items list
}
.receive(on: DispatchQueue.main) // << receive processed items on main queue
.sink { [weak self] (filtered, chosen) in
withAnimation {
self?.filteredItems = filtered // animating this as well
}
}
}

关于swiftui - 组合 + SwiftUI Form + RunLoop 导致表格 View 呈现不可预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67133680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com