首页 > 解决方案 > 如何在 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)")
        }
    }
}

可能是什么问题?

标签: core-dataswiftuipicker

解决方案


这可能是因为您尝试应用于.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)

一个解决方案可能是附加tagHStack

HStack {
    Circle().fill(Color.green)
        .frame(width: 16, height: 16)
    Text("\(level?.name ?? "Unassigned")")
}
.tag(level)

推荐阅读