WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: How to access all attributes of the selected object in a Picker View

Forums > SwiftUI

The following code effectively displays the dog's names and when selecting a dog, it outputs its color. What I would like to do is be able to track what object has been selected and be able to access all its attributes in the onChange method.

How can I access all attributes of the selected object inside the onChange method?

    class Dog:NSObject {
        var name = ""
        var color = ""
        var breed = ""

        init(name: String, color: String, breed: String) {
            self.name = name
            self.color = color
            self.breed = breed
        }
    }

    class DogService:ObservableObject{
        @Published var dogs:[Dog]

        init(){
            dogs = [Dog(name:"Pluto", color: "Brown", breed: "Golden Retriever"),
                    Dog(name: "Teddy", color: "White", breed: "Poodle"),
                    Dog(name: "Rocky", color: "Black", breed: "Labrador")]
        }
    }

    struct PickerTest: View {
        let dogService = DogService()
        @State private var selectedDog = ""

        var body: some View {
            Form {
                Picker("Dogs:", selection: $selectedDog) {
                    ForEach(dogService.dogs, id: \.self) {
                        Text($0.name).tag($0.color)
                    }
                }
                .onChange(of: selectedDog) {dog in
                    print("Dog Color: \(dog)") // outputs, Brown, White or Black

                    // what I would like to do...  
                    // print("Dog Breed: \(dog.breed)") // should output, Golden Retriever, Poodle or Labrador
                }
            }
        }
    }

2      

Hi. Just change your tag to refer to breed instead of color, like so

 var body: some View {
        Form {
            Picker("Dogs:", selection: $selectedDog) {
                ForEach(dogService.dogs, id: \.self) {
                    Text($0.name).tag($0.breed)
                }
            }
            .onChange(of: selectedDog) {dog in
                print("Dog Breed: \(dog)") // outputs, Brown, White or Black

                // what I would like to do...
                // print("Dog Breed: \(dog.breed)") // should output, Golden Retriever, Poodle or Labrador
            }
        }
    }

to access all properties then assign dog object to a tag.

@State private var selectedDog = Dog(name: "", color: "", breed: "")

    var body: some View {
        Form {
            Picker("Dogs:", selection: $selectedDog) {
                ForEach(dogService.dogs, id: \.self) {
                    Text($0.name).tag($0)
                }
            }
            .onChange(of: selectedDog) {dog in
                print("Dog Breed: \(dog.breed)") // outputs, Brown, White or Black
                print("Dog Color: \(dog.color)")

                // what I would like to do...
                // print("Dog Breed: \(dog.breed)") // should output, Golden Retriever, Poodle or Labrador
            }
        }
    }

3      

Here is what I did that worked.

class Dog:NSObject {
    var name = ""
    var color = ""
    var breed = ""

    init(name: String, color: String, breed: String) {
        self.name = name
        self.color = color
        self.breed = breed
    }
}

class DogService:ObservableObject{
    @Published var dogs:[Dog]

    init(){
        dogs = [Dog(name:"Pluto", color: "Brown", breed: "Golden Retriever"),
                Dog(name: "Teddy", color: "White", breed: "Poodle"),
                Dog(name: "Rocky", color: "Black", breed: "Labrador")]
    }
}

struct PickerTest: View {
    @StateObject var dogService = DogService()
    @State private var selectedDog:Dog?

    var body: some View {
        Form {
            Picker("Dogs:", selection: $selectedDog) {
                ForEach(dogService.dogs, id: \.self) {
                    Text($0.name).tag($0 as Dog?)
                }
            }
            .onChange(of: selectedDog) {dog in
                print("Dog Color: \(dog?.breed)")
            }
        }
    }
}

2      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.