收到错误!!选择器:选择“nil”无效且没有关联的标签,这将给出未定义的结果

getting error !! Picker: the selection "nil" is invalid and does not have an associated tag, this will give undefined results

提问人:Smit Patel 提问时间:8/8/2023 最后编辑:vadianSmit Patel 更新时间:8/8/2023 访问量:107

问:

这是我的主要文件在选取器中出错,无法从选取器中选择值,在第一个选取器中出错

import SwiftUI

struct MainView: View { 
    @ObservedObject private var branchSelectionViewModel = BranchSelectionViewModel() 
    @StateObject private var semesterSelectionViewModel = SemesterSelectionViewModel() 
    @StateObject private var subjectListViewModel = SubjectListViewModel() 
    @StateObject private var paperListViewModel = PaperListViewModel()

var body: some View {
    NavigationView {
        ScrollView {
            VStack {
                Picker("Select Branch", selection: $branchSelectionViewModel.selectedBranch) {
                    ForEach(branchSelectionViewModel.branches, id: \.id) { branch in
                        Text(branch.name).tag(branch)
                    }
                }
                .pickerStyle(.menu)
                
                
                
                Picker("Select Semester", selection: $semesterSelectionViewModel.selectedSemester) {
                    ForEach(semesterSelectionViewModel.semesters, id: \.id) { semester in
                        Text(semester.name).tag(semester)
                    }
                }
                .pickerStyle(.wheel)
                
                if let selectedBranch = branchSelectionViewModel.selectedBranch,
                   let selectedSemester = semesterSelectionViewModel.selectedSemester {
                    SubjectListView(viewModel: subjectListViewModel,
                                    branchId: selectedBranch.id,
                                    semesterId: selectedSemester.id)
                }
            }
        }
        .onAppear {
            branchSelectionViewModel.fetchBranches()
        }
        .navigationTitle("Previous Year Papers")
    }
}
}

下面的代码是 BranchSelectionViewModel,选取器从中选择分支,但在终端中收到消息“Picker:选择”nil“无效且没有关联的标记,这将给出未定义的结果”


class BranchSelectionViewModel: ObservableObject {
    @Published var branches: [Branch] = []
    @Published var selectedBranch: Branch?
    
    func fetchBranches() {
        // Simulate fetching branches from a network or database
        branches = [
            Branch(id: 1, name: "Computer Science"),
            Branch(id: 2, name: "Electrical Engineering"),
            // ... add more branches ...
        ]
    }
}
iOS SwiftUI swiftUI 选择器

评论


答:

0赞 vadian 8/8/2023 #1

selectedBranch是可选的,它可以是 .但是没有相应的标签 Nothing selected aka .nilnil

一种可能的解决方案是将默认值设置为非可选值,例如 。将新分支追加到数组中,并在数组变为空时恢复默认值。或者仅当数组为空时才使用默认值。selectedBranchBranch(id: 0, name: "None")

旁注:

始终用于视图所拥有的对象。
是等效于 的引用类型。
@StateObject@ObservedObject@Binding