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

Picker with Menu does not work with Int32 but it works with Int

This code does not work, meaning onChange is never called and the variable is not changed when a dropdown option is selected.

struct ExamplePicker: View {
    
    @State var val: Int32 = 2
    
    var body: some View {
        HStack {
            
            Menu {
                
                Picker(selection: $val, label: EmptyView()) {
                    
                    Text("Val1").tag(1)
                    Text("Val2").tag(2)
                    Text("Val3").tag(3)
                }
                
                
            } label: {
                HStack {
                    Text("Value: ")
                    Spacer()
                    
                    Text(String(format: "%d", val))
                    
                    Spacer()
                }
                
            }
            .onChange(of: val) { newSelection in
               print(">>> HERE")
           }
            
            
        }
        
    }
}

but if you change val to type Int it works perfectly fine. Int64 also works with no problem.
This looks like a bug to me

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

>Solution :

It works fine when the tag values of the Picker items have the same type as the state variable. Like this:

Picker(selection: $val, label: EmptyView()) {
    Text("Val1").tag(Int32(1))
    Text("Val2").tag(Int32(2))
    Text("Val3").tag(Int32(3))
}
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