0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

激重なリストの更新をアニメ処理無効化で軽くする

Last updated at Posted at 2020-05-04

list filtering example1

import SwiftUI

struct ContentView: View {
    private var items = Array(1...20)
    @State var word = ""
    var filteredItems: [Int] {
        word.isEmpty ? items : items.filter{"\($0)".contains(word)}
    }
    var body: some View {
        VStack {
            TextField("Search", text: $word)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .frame(width: 300)
                .padding()
            List(filteredItems, id: \.self) {
                Text("item \($0)")
            }
        }
    }
}

少ないアイテム数ならアニメーション/トランジション効果があっても問題はないが、アイテムが増えると重くなり最悪フリーズ状態に。

重くなる原因は表示変更の効果計算がアイテム毎に行われている為。

その計算を行わないようにする為に新たにリストを作り出して入れ替えるという形にすると瞬時に表示される。

具体的にはList{〜}.id(UUID())と更新の度にユニークidを付加するだけ。

import SwiftUI

struct ContentView: View {
    private var items = Array(1...10000)
    @State var word = ""
    var filteredItems: [Int] {
        word.isEmpty ? items : items.filter{"\($0)".contains(word)}
    }
    var body: some View {
        VStack {
            TextField("Search", text: $word)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .frame(width: 300)
                .padding()
            List(filteredItems, id: \.self) {
                Text("item \($0)")
            }.id(UUID())
        }
    }
}

list filtering example2

ネタ元: https://www.hackingwithswift.com/articles/210/how-to-fix-slow-list-updates-in-swiftui

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?