Skip to content

Instantly share code, notes, and snippets.

@sidepelican
Last active June 5, 2019 03:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidepelican/249678dd2d57436d483c49fc0c49765c to your computer and use it in GitHub Desktop.
Save sidepelican/249678dd2d57436d483c49fc0c49765c to your computer and use it in GitHub Desktop.
SwiftUI List rebuild test
import SwiftUI
struct User: Identifiable {
var id: Int
init(id: Int) {
self.id = id
}
}
struct MyCell: View {
let user: User
private let randomHeight: Length
init(user: User) {
self.user = user
randomHeight = Length.random(in: 4...6) * 10
// randomHeight = 50
print("MyCell initialized. id:", user.id)
}
var body: some View {
print("MyCell builded. id:", user.id)
return Text(String(user.id))
.frame(height: randomHeight, alignment: .center)
}
}
struct ContentView : View {
var users: [User] = (0..<100).map(User.init(id:))
@State var selected: Set<Int> = []
var body: some View {
List(users, selection: $selected, action: { user in
if self.selected.contains(user.id) {
print(user.id, "will remove")
self.selected.remove(user.id)
print(user.id, "did remove")
} else {
print(user.id, "will add")
self.selected.insert(user.id)
print(user.id, "did add")
}
}) { user in
MyCell(user: user)
.background(self.selected.contains(user.id) ? Color.red : Color.white)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment