【问题标题】:Flickering with .searchable List闪烁 .searchable 列表
【发布时间】:2022-10-01 10:10:10
【问题描述】:

例如,您需要在 SPM 中添加LoremSwiftum

我发现在使用List的.init(_:id:rowContent:)构造函数时,搜索字段中的行项闪烁。

Video of what it looks like

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()) 也会使闪烁消失,尽管这也存在一些问题。

那么,如何使用正确的 List 构造函数并且在搜索时不会出现可怕的项目闪烁?

  • 找到任何解决方案了吗?我正在使用 UUID,但问题仍然存在

标签: swiftui swiftui-list


【解决方案1】:

尝试至少避免可识别列表的计算属性。 我有列表项的下一个对象:

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
    }
}

【讨论】:

    【解决方案2】:

    我正在使用以下代码,但没有遇到闪烁。

    struct ContentView: View {
        
        @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.isEmpty ? words: 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())})
                    }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-01
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多