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

Why the return value in closure didn't cover the binded one in SwiftUI?

Here is my code in Swift

import SwiftUI

struct Contentview: View {
@State private var numberOfPeople = 2
 Section {
    Picker("Number of Person", selection: $numberOfPeople) {
           ForEach(2..<10) {
               Text("\($0) people")
            }
     }
                   
    Text("\(numberOfPerson) people")
   }


}

Number of people should be at least 2, and with a max of 10.
I bind the valuenumberOfPeople in Picker, and I show the value numberOfPeople in Text, but the actual value of numberOfPeople are alway 2 less than the value I shown in Picker

Check out this picture

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 :

Approach:

  • You are not tagging your views
  • You need to add tag($0)

Code:

struct ContentView: View {
    @State private var numberOfPerson = 2
    
    var body: some View {
        Section {
            Picker("Number of Person", selection: $numberOfPerson) {
                ForEach(2..<10) {
                    Text("\($0) people")
                        .tag($0) //Fix
                }
            }
            
            Text("\(numberOfPerson) people")
        }
    }
}
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