我有这个
AddWorkoutView
,我正在尝试构建一些类似于苹果对“添加新联系人”表单所做的表单。
现在我正在尝试添加一个比简单的TextField
更复杂的表单(类似于Apple联系人中的“添加地址”,但我面临以下问题:
Picker
和删除 Button
,并且 Picker
一旦打开并且所选条目会自动关闭。返回AddWorkoutView
时也删除了。有谁知道苹果是如何实现这种复杂的形式的,就像下面的屏幕显示一样?
感谢RogerTheShrubber回复here我设法以某种方式至少实现了添加按钮并动态显示我之前添加的所有内容,但我不知道以相同的形式将多个文本字段/选择器/任何其他内容组合在一起.
struct AddWorkoutView: View {
@EnvironmentObject var workoutManager: WorkoutManager
@EnvironmentObject var dateModel: DateModel
@Environment(\.presentationMode) var presentationMode
@State var workout: Workout = Workout()
@State var exercises: [Exercise] = [Exercise]()
func getBinding(forIndex index: Int) -> Binding<Exercise> {
return Binding<Exercise>(get: { workout.exercises[index] },
set: { workout.exercises[index] = $0 })
}
var body: some View {
NavigationView {
Form {
Section("Workout") {
TextField("Title", text: $workout.title)
TextField("Description", text: $workout.description)
}
Section("Exercises") {
ForEach(0..<workout.exercises.count, id: \.self) { index in
HStack {
Button(action: { workout.exercises.remove(at: index) }) {
Image(systemName: "minus.circle.fill")
.foregroundColor(.red)
.padding(.horizontal)
}
Divider()
VStack {
TextField("Title", text: $workout.exercises[index].title)
Divider()
Picker(selection: getBinding(forIndex: index).type, label: Text("Type")) {
ForEach(ExerciseType.allCases, id: \.self) { value in
Text(value.rawValue)
.tag(value)
}
}
}
}
}
Button {
workout.exercises.append(Exercise())
} label: {
HStack(spacing: 0) {
Image(systemName: "plus.circle.fill")
.foregroundColor(.green)
.padding(.trailing)
Text("add exercise")
}
}
}
}
.navigationTitle("Create new Workout")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button {
presentationMode.wrappedValue.dismiss()
} label: {
Text("Cancel")
}
.accessibilityLabel("Cancel adding Workout")
}
ToolbarItem(placement: .confirmationAction) {
Button {
} label: {
Text("Done")
}
.accessibilityLabel("Confirm adding the new Workout")
}
}
}
}
}
我在将
Button
放在 Picker
旁边并放在 HStack
中包含的同一个 Form
中时遇到了类似的问题。
这个苹果开发者论坛帖子给我带来了解决方案/解决方法:只需添加
.buttonStyle(BorderlessButtonStyle())