【问题标题】:Setting a default value for an NSManagedObject in SwiftUI Picker?在 SwiftUI Picker 中为 NSManagedObject 设置默认值?
【发布时间】:2020-08-17 01:14:13
【问题描述】:

我正在使用 SwiftUI 中的 Picker 从核心数据列表NSManagedObjects 中进行选择,但无法让选择器显示默认值。选择后也不会设置新值。有没有办法让选择器显示默认值?

这里是设置我的 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)
                        }
                    }
                }
                //...
            }
        }
        //...
    }
}

【问题讨论】:

    标签: swiftui swiftui-form


    【解决方案1】:

    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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      相关资源
      最近更新 更多