[英]Core Data results into a SwiftUI Picker view without preselecting an option
I am fetching data from Core Data and displaying it in a Picker, this view is built in SwiftUI.我正在从 Core Data 获取数据并将其显示在 Picker 中,该视图是在 SwiftUI 中构建的。 I struggled at first to get the selection to work from the picker, but found if I preselect the first object from my fetch result, in the view's init, the picker selection works.一开始我努力让选择器从选择器中工作,但发现如果我从我的获取结果中预选第一个对象,在视图的初始化中,选择器选择工作。
What I want is to be able to load my data into the Picker, but not preselect one of the objects.我想要的是能够将我的数据加载到选择器中,但不能预选其中一个对象。 Again, if I update the code below so nothing is preselected, then I can't select anything.同样,如果我更新下面的代码,因此没有预先选择任何内容,那么我将无法选择任何内容。 I get to the screen of options, but when I tap one, nothing happens, I just get that little flash on the row.我进入选项屏幕,但是当我点击一个选项时,什么也没有发生,我只是在行上看到那个小闪光。 I have to hit the Back button to get back to the form view.我必须点击返回按钮才能返回表单视图。
Any ideas for how to make loading Core Data into a Picker without preselecting one of the options work?关于如何在不预先选择其中一个选项的情况下将核心数据加载到选择器中的任何想法?
-Thanks! -谢谢!
import SwiftUI
import CoreData
struct RecordCreateview: View {
@FetchRequest private var actions: FetchedResults<Actions>
@State private var selectedAction: Actions
init(context: NSManagedObjectContext) {
let fetchRequest: NSFetchRequest<Actions> = Actions.fetchRequest()
fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Actions.action, ascending: true)]
fetchRequest.predicate = NSPredicate(value: true)
self._actions = FetchRequest(fetchRequest: fetchRequest)
do {
let fetchResult = try context.fetch(fetchRequest)
self._selectedAction = State(initialValue: fetchResult[0])
} catch {
fatalError("Problem fetching Action records.")
}
}
var body: some View {
NavigationView {
Form {
Picker("Select action", selection: $selectedAction){
ForEach(actions) { action in
if action.title == true {
Text("\(action.action!)").tag(action)
}
}
}
}
}
}
}
You could set the selectedAction
to a non-existent Actions
in init(...)
like this:您可以在init(...)
中将selectedAction
设置为不存在的Actions
,如下所示:
self._selectedAction = State(initialValue: Actions(context: context))
that will not set a pre-selected object in the picker.这不会在选择器中设置预选对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.