Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI Picker from CoreData Values

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading