简体   繁体   中英

SwiftUI Picker doesn't update data when selecting a new row

SwiftUI Picker doesn't update data when selecting a new row. I tried to pass the data via Binding, but it didn't seem to work. When I remove the Binding logic, it all works fine as I expected.

ContentView.swift

import SwiftUI

struct ContentView: View {
    
    var colors = ["Red", "Green", "Blue", "Tartan"]

    @State private var showPicker: Bool = false
    @Binding var selectedColor: String
    
    var body: some View {
        
        PanelView(showPicker: .constant(false))
        
            VStack {
                Picker("Please choose a color", selection: $selectedColor) {
                    ForEach(colors, id: \.self) {
                        Text($0)
                    }
                }
            }
        
    }
}

PanelView.swift

import SwiftUI

struct PanelView: View {

    @Binding var showPicker: Bool
    @State private var selectedColor = "Red"
    
    var body: some View {
        HStack(spacing: 10) {
            Text("You selected: \(selectedColor)")
        }
    }
}

Sorry for my English, hope someone can take a look at this problem.

.constant is a dead end don't use it anywhere but in the Previews section to simulate a source of truth.

@State is a source of truth, it has no parent.

@Binding is a two-way connection. It does not have the ability to hold a value.

import SwiftUI

struct ContentView: View {
    
    var colors = ["Red", "Green", "Blue", "Tartan"]

    @State private var showPicker: Bool = false
    @State private var selectedColor: String = "Red"
    
    var body: some View {
        
        PanelView(showPicker: $showPicker, selectedColor: $selectedColor)
        
            VStack {
                Picker("Please choose a color", selection: $selectedColor) {
                    ForEach(colors, id: \.self) {
                        Text($0)
                    }
                }
            }
        
    }
}

struct PanelView: View {

    @Binding var showPicker: Bool
    @Binding var selectedColor : String
    
    var body: some View {
        HStack(spacing: 10) {
            Text("You selected: \(selectedColor)")
        }
    }
}

Try the Apple SwiftUI Tutorials all of this is pretty basic stuff.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM