对于这个例子,您需要使用SPM添加LoremSwiftum。
我发现在使用List的*id:rowContent:)构造函数时,搜索字段中的行项会闪烁。
import SwiftUI
import LoremSwiftum
let words = Array(Set(Lorem.words(3000).components(separatedBy: " ")))
struct ContentView: View {
@State var searchText = ""
var searchedWords: [String] {
searchText.isEmpty ? words : Array(words.filter { $0.localizedCaseInsensitiveContains(searchText) }.prefix(50))
}
var body: some View {
NavigationView {
List(searchedWords, id:\.self) { word in
HStack {
Rectangle().frame(width: 50, height: 50).foregroundColor(.red)
Text(word)
}
}
.searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always))
}
}
}使用.indices使闪烁消失,即:
List(searchedWords.indices, id:\.self) { i in
let word = words[I]
...
}尽管据我所知,当项目发生变化时,使用.indices可能会导致问题。
在列表中使用.id(UUID())也会使闪烁消失,尽管这也存在一些问题。
那么,我如何使用列表的正确构造函数,并且在搜索时不会出现可怕的闪烁?
发布于 2022-09-30 19:41:21
尽量避免至少可识别的列表的计算属性。我有下一个用于列表项的对象:
struct Message: Identifiable, Equatable, Codable {
var id: String { UUID().uuidString }
let title: String
let message: String
}它的闪烁与你的例子非常相似。把结构改为下一个解决了我的问题。
struct Message: Identifiable, Equatable, Codable {
let id: String
let title: String
let message: String
init(title: String, message: String) {
self.id = UUID().uuidString
self.title = title
self.message = message
}
}发布于 2022-10-01 02:10:10
我正在使用下面的代码,我不体验闪烁。
结构ContentView:视图{
@State private var words = Array(Set(Lorem.words(3000).components(separatedBy: " ")))
@State private var searchText: String = ""
@State private var filteredWords: [String] = []
var body: some View {
NavigationStack {
List(filteredWords, id: \.self) { word in
HStack {
Rectangle().frame(width: 50, height: 50).foregroundColor(.red)
Text(word)
}
}.searchable(text: $searchText)
.onChange(of: searchText) { search in
filteredWords = words.filter({ $0.starts(with: search.lowercased())})
}
.onAppear {
filteredWords = words
}
}
}}
https://stackoverflow.com/questions/71577864
复制相似问题