UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: State in List items being reset on scroll?

Forums > SwiftUI

I'm very new to Swift and SwiftUI so apologies for the very basic question. I must be misunderstanding something about the SwiftUI lifecycle and it's interaction with @State.

I've have a list, and when you click on the row, it increments a counter. If I click on some row items to increment the counter, scroll down, and scroll back up again - the state is reset to 0 again. Can anyone point out where I'm going wrong? Many thanks.

struct TestView : View {
    @State private var listItems:[String] = (0..<50).map { String($0) }
    var body: some View {
        List(listItems, id: \.self) { listItem in
            TestViewRow(item: listItem)
        }
    }
}

struct TestViewRow: View {
    var item: String
    @State private var count = 0

    var body: some View {
        HStack {
            Button(item, action: {
                self.count += 1
            })
            Text(String(self.count))
            Spacer()
        }
    }
}

2      

If you attach these two modifiers to your HStack in TestViewRow, you can see what's going on:

        .onAppear { print("list row \(item) appeared") }
        .onDisappear { print("list row \(item) disappeared") }

The problem is that the individual TestViewRows are removed when they scroll offscreen and when they reappear the @State is reset to 0. You need to store the counter outside of that view so it doesn't reset on disappear/reappear.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.