SwiftUI Picker 不改变选择值

SwiftUI Picker not changing selection value

以下选择器未更新 $selection。无论选择器在 运行 应用程序时显示什么,selection.rawValue 总是 returns 0.

是什么阻止了 Picker 更新状态变量 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
    }
}

这里有一个适合你的方法:

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