简体   繁体   中英

PickerView disabled and doesn't work in SwiftUI

I don't understand why picker view doesn't work. I used this code:

import SwiftUI

struct NewChecklistItemView: View {

    var colors = ["Red", "Green", "Blue", "Tartan"]
    @State private var selectedColor = 0


  var checklist: Checklist
  @State var newItemName: String = ""
  @Environment(\.presentationMode) var presentationMode

  var body: some View {
    VStack {
      Text("Add new item")
      Form {
        TextField("Enter new item name here", text: $newItemName)
        Picker(selection: $selectedColor, label: Text("Please choose a color")) {
           ForEach(0 ..< colors.count) { 
              Text(self.colors[$0])
           }
        }
        Text("You selected: \(colors[selectedColor])")

        Button(action: {
        //let newChecklistItem = Category(title: "Category", items: [ChecklistItem(name: self.newItemName)])
            let newItem = ChecklistItem(name: self.newItemName)

            self.checklist.items[0].items.append(newItem)
          self.checklist.printChecklistContents()
          self.presentationMode.wrappedValue.dismiss()
        }) {
          HStack {
            Image(systemName: "plus.circle.fill")
            Text("Add new item")
          }
        }
        .disabled(newItemName.count == 0)

      }
      Text("Swipe down to cancel.")
    }
  }
}

struct NewChecklistItemView_Previews: PreviewProvider {
  static var previews: some View {
    NewChecklistItemView(checklist: Checklist())
  }
}

PickerView is grey and disabled. So I cannot pick values. What could be the problem? I tried to move pickerView, but it doesn't help.

To make Picker work in Form you have to embed it into NavigationView , like

NavigationView {
  Text("Add new item")
  Form {
    TextField("Enter new item name here", text: $newItemName)
    Picker(selection: $selectedColor, label: Text("Please choose a color")) {

(of course, this might require some redesign/relayout)... or use different style picker style.

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