2 years ago

#55692

test-img

photosynthesis

Issue with setting @State variable dynamically

As in the code below, the choosenKeyboardKnowledge is a @State variable and was initiated as the first object read from the cache. Then in the body, I iterate each object and wrap it into a Button so that when clicked it leads to the corresponding sheet view. But each time after I run the preview and click on whichever button in the list view it always shows the first default view (set in the initializer), and if I dismiss it and click on another line it shows the correct view.

struct KeyboardKnowledgeView: View {
    var keyboardKnowledges: [KeyboardKnowledge]
    @State private var choosenKeyboardKnowledge: KeyboardKnowledge
    @State private var showSheet: Bool = false

    init() {
        keyboardKnowledges = KeyboardKnowledgeCache.getKeyboardKnowledges()
        _choosenKeyboardKnowledge = State(initialValue: keyboardKnowledges[0])
    }

    var body: some View {
        ZStack {
            Color.bgGreen.ignoresSafeArea()

            List(keyboardKnowledges) { knowledge in
                Button(action: {
                    self.choosenKeyboardKnowledge = knowledge
                    self.showSheet.toggle()
                }) {
                    Text(knowledge.name)
                }
                .sheet(isPresented: $showSheet) {
                    KeyboardKnowledgeDetailsView(keyboardKnowledge: choosenKeyboardKnowledge)
                }
            }
        }
    }

}

swift

swiftui

swiftui-list

0 Answers

Your Answer

Accepted video resources