Dillon
Dillon

Reputation: 1

Why is my picker displaying the array reversed?

I'm learning Swift and I came across this problem. I made an array for US states, and when I pass it in the picker for some reason it just reverses it. I solved it temporarily by reversing the states array, but why did it happen? How do pickers work in this context? Any ways to actually solve it? Thanks to anyone who takes time to respond.

import SwiftUI

struct CountryPicker: View {
    @State private var selectedCountry = ""
    let states = [
        "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia",
        "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland",
        "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey",
        "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina",
        "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"
    ]
    
    var body: some View {
        Menu {
            Menu("North America") {
                Picker(selection: $selectedCountry, label: Text("North America")) {
                    Menu("United States") {
                        Picker(selection: $selectedCountry, label: Text("United States")) {
                            ForEach(states, id: \.self) { state in
                                Text(state).tag(state)
                            }
                        }
                    }
                    Text("Canada")
                }
            }
            Menu("Europe") {
                Picker(selection: $selectedCountry, label: Text("Europe")) {
                    Text("Italy")
                }
            }
        } label: {
            Label("Select Country", systemImage: "globe")
        }
        .padding()
        .onAppear {
            // Debugging: Check the sorted order
            let sortedStates = states.sorted()
            print("Sorted States: \(sortedStates)") // Debug output to console
        }
    }
}

#Preview {
    CountryPicker()
}

Upvotes: 0

Views: 76

Answers (1)

Benzy Neez
Benzy Neez

Reputation: 21730

If the menu is shown in the space above the picker (as opposed to below it) then it may be shown "upside down". This represents "priority" order, which aims to keep the first items closer to the user’s point of interaction.

You can override this behavior by applying .menuOrder(.fixed):

CountryPicker()
    .menuOrder(.fixed)

Screenshot

Upvotes: 5

Related Questions