【问题标题】:SwiftUI Picker return empty string from CoreDataSwiftUI Picker 从 CoreData 返回空字符串
【发布时间】:2020-08-06 09:15:24
【问题描述】:

如何改进?当我使用ForEach(CoreData 实体)时,选择器返回空字符串。如果我使用 testing[String] 一切正常

import SwiftUI

struct AddTask: View {
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(entity: Goal.entity(), sortDescriptors: []) var goals: FetchedResults<Goal>
    
    @State private var taskName: String = ""
    @State private var originGoal = ""
    private let testGoal = ["Alpha", "Bravo", "Charlie"]
    
    var body: some View {
        NavigationView {
            Form {
                Section{
                    TextField("Enter Task Name", text: $taskName)
                }
                Section {
                    Picker(selection: $originGoal, label: Text("Choose Goal")) {
                        ForEach(goals, id: \.self) { goal in
                            Text(goal.wrappedName)
                        }
                    }
                }
            }
        }
        
        Button("Add") {
            let task1 = Task(context: self.moc)
            task1.name = taskName
            task1.origin = Goal(context: self.moc)
            task1.origin?.name = originGoal
            
            try? self.moc.save()
        }
    }
}

或者也许 SwiftUI Picker 有不错的替代品?

【问题讨论】:

  • Picker return empty String 是什么意思?
  • 选择器不要从目标列表中选择任何变体,显示,但不要选择

标签: core-data swiftui picker


【解决方案1】:

selectionid 应该是Picker 中的相同类型,所以试试(无法测试您的代码):

Section {
    Picker(selection: $originGoal, label: Text("Choose Goal")) {
        ForEach(goals, id: \.wrappedName) { goal in
            Text(goal.wrappedName)
        }
    }
}

有时tag 也有效(但并非总是如此),所以也试试

Section {
    Picker(selection: $originGoal, label: Text("Choose Goal")) {
        ForEach(goals, id: \.self) { goal in
            Text(goal.wrappedName).tag(goal.wrappedName)
        }
    }
}

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 2020-01-27
    • 2020-07-11
    • 2015-05-25
    • 2011-05-09
    相关资源
    最近更新 更多