1

我正在使用PickerSwiftUI 从 Core Data 列表中进行选择NSManagedObject,并且无法让选择器显示默认值。选择后也不会设置新值。有没有办法让选择器显示默认值?

这是我的 NSManagedObject 属性设置的地方。

extension Company {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Company> {
        return NSFetchRequest<Company>(entityName: "Company")
    }

    @NSManaged public var id: UUID?
    @NSManaged public var name: String?
    @NSManaged public var companyContacts: NSSet?
    @NSManaged public var companyRoles: NSSet?

    //...

}

这就是我尝试使用它的地方。

struct AddRoleSheet: View {
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(
        entity: Company.entity(),
        sortDescriptors: [
            NSSortDescriptor(keyPath: \Company.name, ascending: true)
        ]
    ) var companies: FetchedResults<Company>

//...

@State var company: Company? = // Can I put something here? Would this solve my problem?

//...

var body: some View {
    NavigationView {
        Form {
            Section {
                Picker(selection: $company, label: Text("Company")) {
                    List {
                        ForEach(companies, id: \.self) { company in
                            company.name.map(Text.init)
                        }
                    }
                }
                //...
            }
        }
        //...
    }
}
4

1 回答 1

0

View.init 阶段还没有获取到结果,所以试试下面的

@State var company: Company? = nil   // << just initialize

//...

var body: some View {
    NavigationView {
        Form {
            Section {
                Picker(selection: $company, label: Text("Company")) {
                    List {
                        ForEach(companies, id: \.self) { company in
                            company.name.map(Text.init)
                        }
                    }
                }
                //...
            }
        }
    }.onAppear {
       // here companies already fetched from database
       self.company = self.companies.first      // << assign any needed
    }
}
于 2020-08-17T03:35:12.687 回答