SwiftUI @Binding update doesn't refresh view

前端 未结 5 2117
一个人的身影
一个人的身影 2021-02-19 21:31

I feel like I\'m missing something very basic, but this example SwiftUI code will not modify the view (despite the Binding updating) when the button is clicked

Tutorials

5条回答
  •  忘掉有多难
    2021-02-19 21:50

    In the top Level of SwiftUI, @Binding cannot refresh View hierarchy unless manually adding a @state or other refreshing triggers.

    struct ContentView: View {
        @Binding var isSelected : Bool
        @State var hiddenTrigger = false
    
        var body: some View {
            VStack {
                Text("\(hiddenTrigger ? "" : "")")
                Button(action: {
                    self.isSelected.toggle()
                    self.hiddenTrigger = self.isSelected
                }) {
                    Text(self.isSelected? "Selected" : "not Selected")
                }
            }
        }
    }
    
    struct ContentView_Previews: PreviewProvider {
                
        static var selected: Bool = false
                
        static var previews: some View {
            ContentView(isSelected: Binding(get: {selected}, set: { newValue in
            selected = newValue}))
        }
    }
    

提交回复
热议问题