简体   繁体   中英

SwiftUI Picker not changing selection value

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

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

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