0

I have a Picker inside a View:

       Form {
            Section {
                Picker("Style instance:", selection: $global.selectedStyle) {
                    ForEach(global.axes.instances.indices, id:\.self) { index in
                        return HStack {
                            let instance = global.axes.instances[index]
                            Text("\(instance.name)")//.tag(index)
                            Spacer()
                            Text(" \(instance.coordinates.description)")
                        }
                    }
                }
                .pickerStyle(PopUpButtonPickerStyle())
            }
        }

global is an defined as an @ObservedObject, inside:

@Published public var selectedStyle: StyleInstance? {
    didSet {
        print ("Changed \(selectedStyle?.description ?? "Nothing selected")")
        if let selected = selectedStyle {
            for index in axes.indices {
                axes[index].at =  Double(selected.coordinates[index])
            }
        }
    }
}

StyleInstance is simple struct:

public struct StyleInstance: Hashable, Codable {
    
    public static var emptyName = "<normal>" //this string will be replaced by empty string
    public let name: String
    public let coordinates: [Int]

    // init removes word `<normal>` and spaces
    init(name: String, coordinates:[CoordUnit]) {
        self.name = name.split(separator: " ").filter({$0 != StyleInstance.emptyName}).joined(separator: " ")
        self.coordinates = coordinates.map {Int($0)}
    }
}

When I change selection in Picker, selectedInstance .. {didSet.. is fired, but it's always nil

1 Answer 1

4

You need to apply a .tag modifier to the HStack inside the ForEach. Since your selection binding is to an Optional<StyleInstance>, you need to force the tag values to be optional also:

ForEach(global.axes.instances.indices, id:\.self) { index in
    return HStack {
        let instance = global.axes.instances[index]
        Text("\(instance.name)")//.tag(index)
        Spacer()
        Text(" \(instance.coordinates.description)")
    }.tag(global.axes.instances[index] as Optional)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.