Home > Net >  SwiftUI Picker not changing selection value
SwiftUI Picker not changing selection value

Time:03-18

The following picker isn't updating $selection. Regardless of what the Picker shows while running the app, selection.rawValue always returns 0.

What is preventing the Picker from updating the State variable selection?

import SwiftUI

struct OrderPicker: View {
    
    let initialIndex: Int
    @State private var selection: Index
    
    enum Index: Int, CaseIterable, Identifiable {
        case none = 0,
             first = 1,
             second = 2,
             third = 3
        var id: Self { self }
    }
    
    init(initialIndex: Int) {
        self.initialIndex = initialIndex
        _selection = State(initialValue: OrderPicker.Index(rawValue: initialIndex) ?? .none)
    }
    
    var body: some View {
        Form {
            Picker("Order in list", selection: $selection) {
                ForEach(Index.allCases) { index in
                    Text(String(describing: index)).tag(index)
                }
            }
        }
        .frame(height: 116)
    }
    
    func getOrderIndex() -> Int {
        let index = selection.rawValue
        return index
    }
}

CodePudding user response:

Here is an approach for you:

struct ContentView: View {
    
    @State private var selection: PickerType = PickerType.none
    
    var body: some View {
        
        OrderPicker(selection: $selection)
    }
}

struct OrderPicker: View {
    
    @Binding var selection: PickerType
    
    var body: some View {
        Form {
            Picker("Order in list", selection: $selection) {
                ForEach(PickerType.allCases, id: \.self) { item in
                    Text(item.rawValue)
                    
                }
            }
            .pickerStyle(WheelPickerStyle())
            .onChange(of: selection, perform: { newValue in
                print(newValue.rawValue, newValue.intValue)
            })
        }
        
    }

}

enum PickerType: String, CaseIterable {
    
    case none, first, second, third
    
    var intValue: Int {
        switch self {
        case .none: return 0
        case .first: return 1
        case .second: return 2
        case .third: return 3
        }
    }
    
}

CodePudding user response:

give your Picker a style, such as:

 .pickerStyle(.menu)

or any other option, but not .automatic

  • Related