我有以下观点:
import SwiftUI
struct ChangePropertiesView: View {
@EnvironmentObject var settings: UserSettings
@State var currentPost: Post
@State private var departmentSelectionId = 0
var body: some View {
VStack(alignment: .leading){
LabeledContent("Priority",value: currentPost.prioritytitle)
HStack {
Text("Department:")
Spacer()
Picker("Change department", selection: $departmentSelectionId) {
ForEach(settings.departmentList, id: \.id) { department in
Text(department.title)
}
} .onAppear(perform: {
updateDepartmentSelection()
})
}
}
}
func updateDepartmentSelection() {
for department in settings.departmentList {
if department.id == currentPost.departmentid {
departmentSelectionId = department.id
debugPrint("Setting correct department to: \(departmentSelectionId)")
}
}
}
我通过使用 api 获取适当的数据来接收部门信息,而 Picker 抱怨说,departmentSelectionId = 0 不正确,因为它不存在。错误是:
“选择器:选择“0”无效并且没有关联的标签,这将给出未定义的结果。”
我正在使用 onAppear 函数来正确选择部门,但这个错误让我很恼火。有没有办法让它安静下来?
您可能想向选择器项目添加标签(在
ForEach
内):
Text(department.title)
.tag(department.id)
如果部门项目实施
Identifiable
,则这并不是绝对必要的。但如果是这种情况,您也不需要识别 id
中的 ForEach
。
但是,这可能无法解决问题 - 除非有 id 为 0 的部门,否则您仍然会收到错误。您需要将
departmentSelectionId
的初始值设置为有效的部门 id,而不是0. 一种可能是将其设置为集合中第一个部门的 id:
@State private var departmentSelectionId =
settings.departmentList.first?.id ?? 0
或者,一个更简单的选项可能是从
Picker
中排除 HStack
,直到状态变量具有有效值:
HStack {
// initial content as before
if departmentSelectionId > 0 {
// Picker here
}
}
.onAppear {
updateDepartmentSelection()
}
顺便说一句,在函数
updateDepartmentSelection
中,一旦确定了正确的 id,您可能想跳出循环。