简体   繁体   English

PickerView 已禁用且在 SwiftUI 中不起作用

[英]PickerView disabled and doesn't work in SwiftUI

I don't understand why picker view doesn't work.我不明白为什么选择器视图不起作用。 I used this code:我使用了这个代码:

import SwiftUI导入 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. PickerView 为灰色且已禁用。 So I cannot pick values.所以我不能选择值。 What could be the problem?可能是什么问题呢? I tried to move pickerView, but it doesn't help.我试图移动pickerView,但没有帮助。

To make Picker work in Form you have to embed it into NavigationView , like要使PickerForm工作,您必须将其嵌入到NavigationView ,例如

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. (当然,这可能需要一些重新设计/重新布局)...或使用不同的样式选择器样式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM