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

Time:08-15

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.

CodePudding user response:

.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.

  • Related