我一直在写我的第一个SwiftUI应用程序,该应用程序管理一个藏书。它的List
大约有3,000个项目,可以非常有效地加载和滚动。如果使用切换控件过滤列表以仅显示我没有UI的书在更新前冻结了20到30秒,这可能是因为UI线程正忙于决定是否显示3,000个单元格中的每一个。 / p>
在SwiftUI中,有没有很好的方法来处理对大列表的更新?
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showWantsOnly) {
Text("Show wants")
}
ForEach(userData.bookList) { book in
if !self.userData.showWantsOnly || !book.own {
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
}.navigationBarTitle(Text("Books"))
}
答案 0 :(得分:3)
您是否尝试过将过滤后的数组传递给ForEach。像这样:
ForEach(userData.bookList.filter { return !$0.own }) { book in
NavigationLink(destination: BookDetail(book: book)) { BookRow(book: book) }
}
事实证明,这确实是一个丑陋,丑陋的错误:
代替过滤数组,我只是在翻转开关时一起移除了ForEach,并用简单的Text("Nothing")
视图替换了它。结果是一样的,需要30秒!
struct SwiftUIView: View {
@EnvironmentObject var userData: UserData
@State private var show = false
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showWantsOnly) {
Text("Show wants")
}
if self.userData.showWantsOnly {
Text("Nothing")
} else {
ForEach(userData.bookList) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
}.navigationBarTitle(Text("Books"))
}
}
我确实找到了一种可以快速运行的解决方法,但是它需要一些代码重构。 “魔术”通过封装发生。解决方法迫使SwiftUI完全丢弃列表,而不是一次删除一行。通过在两个单独的封装视图中使用两个单独的列表来做到这一点:Filtered
和NotFiltered
。以下是包含3000行的完整演示。
import SwiftUI
class UserData: ObservableObject {
@Published var showWantsOnly = false
@Published var bookList: [Book] = []
init() {
for _ in 0..<3001 {
bookList.append(Book())
}
}
}
struct SwiftUIView: View {
@EnvironmentObject var userData: UserData
@State private var show = false
var body: some View {
NavigationView {
VStack {
Toggle(isOn: $userData.showWantsOnly) {
Text("Show wants")
}
if userData.showWantsOnly {
Filtered()
} else {
NotFiltered()
}
}
}.navigationBarTitle(Text("Books"))
}
}
struct Filtered: View {
@EnvironmentObject var userData: UserData
var body: some View {
List(userData.bookList.filter { $0.own }) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
struct NotFiltered: View {
@EnvironmentObject var userData: UserData
var body: some View {
List(userData.bookList) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
struct Book: Identifiable {
let id = UUID()
let own = Bool.random()
}
struct BookRow: View {
let book: Book
var body: some View {
Text("\(String(book.own)) \(book.id)")
}
}
struct BookDetail: View {
let book: Book
var body: some View {
Text("Detail for \(book.id)")
}
}
答案 1 :(得分:2)
我认为我们必须等到随后的beta版本中的SwiftUI List性能提高。当列表从非常大的数组(超过500个)过滤到很小的数组时,我也遇到了同样的滞后。我创建了一个简单的测试应用,为带有整数ID和带有Buttons的字符串的简单数组安排时间,以简单地更改要渲染的数组-相同的滞后时间。
答案 2 :(得分:2)
查看本文https://www.hackingwithswift.com/articles/210/how-to-fix-slow-list-updates-in-swiftui
简而言之,本文提出的解决方案是将 .id(UUID())添加到列表中:
List(items, id: \.self) {
Text("Item \($0)")
}
.id(UUID())
“”现在,使用id()这样有一个弊端:您不会使更新动起来。记住,我们实际上是在告诉SwiftUI旧列表已经消失,现在有了新列表,这意味着它不会尝试以动画方式移动行。”
答案 3 :(得分:1)
代替复杂的解决方法,只需清空List数组,然后设置新的filters数组。可能有必要引入一个延迟,以便随后的写入操作不会遗漏清空listArray。
List(listArray){item in
...
}
self.listArray = []
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
self.listArray = newList
}
答案 4 :(得分:0)
如果您按以下方式在“ SceneDelegate”文件中初始化类,则此代码将正确运行:
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
var userData = UserData()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView:
contentView
.environmentObject(userData)
)
self.window = window
window.makeKeyAndVisible()
}
}
答案 5 :(得分:0)
寻找如何让Seitenwerk的响应适应我的解决方案,我找到了一个Binding扩展,对我有很大帮助。这是代码:
struct ContactsView: View {
@State var stext : String = ""
@State var users : [MockUser] = []
@State var filtered : [MockUser] = []
var body: some View {
Form{
SearchBar(text: $stext.didSet(execute: { (response) in
if response != "" {
self.filtered = []
self.filtered = self.users.filter{$0.name.lowercased().hasPrefix(response.lowercased()) || response == ""}
}
else {
self.filtered = self.users
}
}), placeholder: "Buscar Contactos")
List{
ForEach(filtered, id: \.id){ user in
NavigationLink(destination: LazyView( DetailView(user: user) )) {
ContactCell(user: user)
}
}
}
}
.onAppear {
self.users = LoadUserData()
self.filtered = self.users
}
}
}
这是Binding扩展名:
extension Binding {
/// Execute block when value is changed.
///
/// Example:
///
/// Slider(value: $amount.didSet { print($0) }, in: 0...10)
func didSet(execute: @escaping (Value) ->Void) -> Binding {
return Binding(
get: {
return self.wrappedValue
},
set: {
execute($0)
self.wrappedValue = $0
}
)
}
}
LazyView是可选的,但我花了很多时间来展示它,因为它对列表的性能有很大帮助,并阻止swiftUI创建整个列表的NavigationLink目标内容。
struct LazyView<Content: View>: View {
let build: () -> Content
init(_ build: @autoclosure @escaping () -> Content) {
self.build = build
}
var body: Content {
build()
}
}