core-data - 如何在 SwiftUI 中的 Picker 选择所在的同一行包含一个 Circle,例如 HStack?
问题描述
在模拟我的应用程序时,我有一个选择器的代码,(Form
这样我会得到选择的导航视图):
Picker("Training Group", selection: $numberOfPeople) {
ForEach(2 ..< 10) { number in
HStack {
Circle().fill(Color.systemYellow)
.frame(width: 16, height: 16)
Text("Group \(number)")
}
}
这很有效:在选择器和随后的导航视图中都有漂亮的小圆圈,就像在 Apple 自己的日历应用程序中一样 - 当为事件选择日历时,每个选择都有自己的颜色“标签”/“标签”。
现在我正在尝试通过使用核心数据的应用程序来实现这一点,但代码不再有效。选择器只接受一个文本视图,其他任何事情都会导致绑定不起作用,并且在我的例子中选择的“级别”不会保存到 managedObjectContext。
这是我的 CoreData 尝试中的结构:
struct AthleteProfile: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Level.name, ascending: true)],
animation: .default)
private var levels: FetchedResults<Level>
@ObservedObject var athlete: Athlete
var body: some View {
Form {
Text(athlete.lastName ?? "Unknown")
Picker("Level", selection: $athlete.level) {
ForEach(levels) { (level: Level?) in
/// I want to place this Text view into an HStack like this:
HStack {
Circle().fill(Color.green)
.frame(width: 16, height: 16)
Text("\(level?.name ?? "Unassigned")").tag(level)
}
/// but the above fails. This below works:
Text("\(level?.name ?? "Unassigned")").tag(level)
/// of course, I use only one of them in the app, the other commented out.
}
}
}
.onDisappear(perform: {
saveContext()
})
}
private func saveContext() {
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
可能是什么问题?
解决方案
这可能是因为您尝试应用于.tag(level)
内部视图:
HStack {
Circle().fill(Color.green)
.frame(width: 16, height: 16)
Text("\(level?.name ?? "Unassigned")").tag(level)
}
下面的示例有效,因为tag
它应用于顶级视图ForEach
:
Text("\(level?.name ?? "Unassigned")").tag(level)
一个解决方案可能是附加tag
到HStack
:
HStack {
Circle().fill(Color.green)
.frame(width: 16, height: 16)
Text("\(level?.name ?? "Unassigned")")
}
.tag(level)
推荐阅读
- google-apps-script - 是否可以使用 IMPORTXML 函数并通过查询对其进行修改?
- c# - 控制台立即使用 CTRL+F5 关闭
- python - 无法在 python 的同一行上打印。print("string here", end = "") 和 print "something", 都不起作用
- ruby-on-rails - How to get a list of a values from a single ActiveRecord column?
- java - 使用自动换行:飞碟中的断词
- java - Gradle不生成jar
- audio - ffmpeg 脚本切断声音
- c++ - 如何改进我的代码以生成安全的随机数?
- javascript - 尝试在对象上调用 get 时 Javascript 不会引发错误
- ruby-on-rails - 如何验证从一个 Rails 应用程序发送到另一个应用程序的请求