选择器中的SwiftUI和enum



我在操场上学习SwiftUI。我正在创建一个视图,其中包括一个标签,一个文本字段,显示选择器和选择器的值的文本。

目前我得到的是这个

import UIKit
import PlaygroundSupport
import SwiftUI
enum Units: String, CaseIterable, Identifiable
{
case Inches = "in"
case Millimeters = "mm"
case Centimeters = "cm"

var id: String { self.rawValue }
}
struct VariableView: View
{
let name: String
let labelValue: String
@State private var inputValue = ""
@State private var inputUnits = Units.Inches

init(name: String, label: String)
{
self.name = name
labelValue = label
}

var body: some View
{
VStack(alignment: .leading, spacing: 0)
{
Text(self.labelValue)
.font(.subheadline)
.frame(width: .infinity, alignment: .leading)
.padding(.horizontal, 4)
HStack
{
TextField("Value", text: $inputValue)
.padding(.horizontal, 4)
.keyboardType(.numbersAndPunctuation)
Text(inputUnits.id)
Picker("...", selection: $inputUnits)
{
/*
Text("Inches").tag(Units.Inches)
Text("Millimeters").tag(Units.Millimeters)
Text("Centimeters").tag(Units.Centimeters)
*/
ForEach(Units.allCases)
{
unit in Text(unit.rawValue.capitalized)
}
}
.padding(10)
.pickerStyle(MenuPickerStyle())
}
Divider()
.frame(height: 1)
.padding(.horizontal, 30)
.background(Color.black)
}
}
}
// Make a SwiftUI view
struct ContentView: View
{
var body: some View
{
VariableView(name: "value1", label: "Value 1")
VariableView(name: "value1", label: "Value 2")
VariableView(name: "value1", label: "Value 3")
VariableView(name: "value1", label: "Value 4")
VariableView(name: "value1", label: "Value 5")
}
}
// Make a UIHostingController
let viewController = UIHostingController(rootView: ContentView())
// Assign it to the playground's liveView
PlaygroundPage.current.liveView = viewController

当我点击"…"时,它崩溃了。变成黑色,停止奔跑。没有错误,只是停止。

如果我使用三行文本(目前被注释掉)代替ForEach,它可以工作-但最终我需要能够动态设置每个输入的允许单位,所以我需要ForEach工作。

inputTypes的类型是Units,硬编码文本上的标记匹配该类型。在ForEach中,标记是Units。rawValue,类型是String。看看这在Playground中是否有效:

struct PickFromEnumView: View {
@State private var inputUnits = Units.none

var body: some View {
VStack {
Picker(inputUnits.rawValue, selection: $inputUnits) {
ForEach(Units.allCases) { unit in
unit.label.tag(unit)
}
}
.padding(10)
.pickerStyle(MenuPickerStyle())
Spacer()
}
}

enum Units: String, CaseIterable, Identifiable
{
case none = "…"
case inches = "in"
case millimeters = "mm"
case centimeters = "cm"

var id: String { self.rawValue }

var label : some View {
switch(self) {
case .none: return Label("…", systemImage: "circle")
case .inches: return Label("inch", systemImage: "1.circle")
case .millimeters: return Label("millimeter", systemImage: "2.circle")
case .centimeters: return Label("centimeter", systemImage: "3.circle")
}
}
}
}

最新更新