Picker for optional data type in SwiftUI?

后端 未结 4 1731
一生所求
一生所求 2021-02-12 16:46

Normally I can display a list of items like this in SwiftUI:

enum Fruit {
    case apple
    case orange
    case banana
}

struct FruitView: View {

    @State          


        
4条回答
  •  抹茶落季
    2021-02-12 17:07

    I made a public repo here with Senseful's solution: https://github.com/andrewthedina/SwiftUIPickerWithOptionalSelection

    EDIT: Thank you for the comments regarding posting links. Here is the code which answers the question. Copy/paste will do the trick, or clone the repo from the link.

    import SwiftUI
    
    struct ContentView: View {
        @State private var selectionOne: String? = nil
        @State private var selectionTwo: String? = nil
        
        let items = ["Item A", "Item B", "Item C"]
        
        var body: some View {
            NavigationView {
                Form {
                    // MARK: - Option 1: NIL by SELECTION
                    Picker(selection: $selectionOne, label: Text("Picker with option to select nil item [none]")) {
                        Text("[none]").tag(nil as String?)
                            .foregroundColor(.red)
    
                        ForEach(items, id: \.self) { item in
                            Text(item).tag(item as String?)
                            // Tags must be cast to same type as Picker selection
                        }
                    }
                    
                    // MARK: - Option 2: NIL by BUTTON ACTION
                    Picker(selection: $selectionTwo, label: Text("Picker with Button that removes selection")) {
                        ForEach(items, id: \.self) { item in
                            Text(item).tag(item as String?)
                            // Tags must be cast to same type as Picker selection
                        }
                    }
                    
                    if selectionTwo != nil { // "Remove item" button only appears if selection is not nil
                        Button("Remove item") {
                            self.selectionTwo = nil
                        }
                    }
                }
            }
        }
    }
    
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }
    

提交回复
热议问题