Home > Back-end >  SwiftUI Picker from CoreData Values
SwiftUI Picker from CoreData Values

Time:03-24

I have a CoreData table called Users that contains, among other things, the name of the user. It's been added to my SwiftUI file with

@Environment(\.managedObjectContext) private var viewContext

@FetchRequest(
    sortDescriptors: [],
    animation: .default)
private var users: FetchedResults<Users>

I have a picker that uses a ForEach loop and populates the picker with the names from the Users table.

@State var selectedUser = ""
Picker("Select user", selection: $selectedUser) {
        ForEach(users) { user in
            Text(user.name!)
        }
    }
    .pickerStyle(.menu)
Text(selectedUser)

Populating the picker does work. However the selected value is not saved properly. When I select something, it doesn't show up in the text area, and in debugging mode, it shows that the selectedUser variable remains the empty string.

I can't seem to figure out how to get this working.

CodePudding user response:

Change your select property to be a User and make it optional (since nothing is selected when the view is opened)

@State var selectedUser: User?

Then you need to use .tag in your picker so the selected user can be correctly assigned to selectedUser

Picker("Select user", selection: $selectedUser) {
    ForEach(users) { user in
        Text(user.name!)
        .tag(Optional(user))
    }
}
.pickerStyle(.menu)

Note that the user variable needs to be made optional in the tag so its type matches the type of selectedUser

  • Related