我正在尝试使用一个选择器来显示当前选中的选项。
尝试以下代码,该代码可以正确选择正确的选项,但选择器不会显示选择了哪个选项:
import SwiftUI
struct ContentView: View {
@State var selectedIndex: Int = 0
let strings: [String] = {
var strings: [String] = []
for i in 0..<10 {
strings.append("\(i)")
}
return strings
}()
var body: some View {
NavigationView {
VStack {
Form {
Picker(selection: $selectedIndex,
label: Text("Selected string: \(strings[selectedIndex])")) {
ForEach(0..<strings.count) {
Text(self.strings[$0]).tag($0)
}
}
}
}
.navigationBarTitle("Form Picker",
displayMode: NavigationBarItem.TitleDisplayMode.inline)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
有人知道可能出什么问题吗?使用Xcode 11.1和iOS 13.1可以观察到
答案 0 :(得分:2)
我创建了一个简单的选择器,我称之为“ ListPicker”,它应该符合要求。我已经编写了它,因此它可以很好地在Form中工作;如果您需要表格之外的内容,则必须进行修改。如果您发现任何改进代码的方法,请添加注释;对于我们所有人来说,这仍然是一次学习经历。
// MARK: - LIST PICKER (PUBLIC)
struct ListPicker<Content: View>: View {
@Binding var selectedItem: Int
var label: () -> Content
var data: [Any]
var selectedLabel: String {
selectedItem >= 0 ? "\(data[selectedItem])" : ""
}
var body: some View {
NavigationLink(destination: ListPickerContent(selectedItem: self.$selectedItem, data: self.data)) {
ListPickerLabel(label: self.label, value: "\(self.selectedLabel)")
}
}
}
// MARK: - INTERNAL
private struct ListPickerLabel<Content: View>: View {
let label: () -> Content
let value: String
var body: some View {
HStack(alignment: .center) {
self.label()
Spacer()
Text(value)
.padding(.leading, 8)
}
}
}
private struct ListPickerContentItem: View {
let label: String
let index: Int
let isSelected: Bool
var body: some View {
HStack {
Text(label)
Spacer()
if isSelected {
Image(systemName: "checkmark")
.foregroundColor(.accentColor)
}
}.background(Color.white) // so the entire row is selectable
}
}
private struct ListPickerContent: View {
@Environment(\.presentationMode) var presentationMode
@Binding var selectedItem: Int
var data: [Any]
var body: some View {
List {
ForEach(0..<data.count) { index in
ListPickerContentItem(label: "\(self.data[index])", index: index, isSelected: index == self.selectedItem).onTapGesture {
self.selectedItem = index
self.presentationMode.wrappedValue.dismiss()
}
}
}
}
}
然后您可以像这样使用它:
@State var selectedCar: Int = 0
let cars = ["Jaguar", "Audi", "BMW", "Land Rover"]
Form {
ListPicker(
selectedItem: self.$selectedCar,
label: {
Text("Cars")
},
data: self.cars
)
}
答案 1 :(得分:1)
这是Xcode 11.1中的错误,只需将其更新为Xcode 11.2,一切都会好