简体   繁体   中英

App to expand 'Other' category when selected on picker from a form (SwiftUI))

I want to provide the user with a list of categories (via picker included in a form) and the last category listed is 'Other'. If the user selects 'Other', the app is to add a field to the form for the user to enter in the new category name (which would be saved for future references).

I have been able to have the picker list presented:

Section {
    Picker(selection: $courseIndex, label: Text("Course")) {
        ForEach(0 ..< courses.count) {
            Text(self.courses[$0]).tag($0)
        } //ForEach
    } // Picker                    
} // Section - Course

But I am unable to determine how to have the new field presented for the user to enter in the new category.

Thanks.

You can add use if in the BodyBuilder, example:

struct ContentView: View {
    @State var courseIndex: Int = 2
    
    let courses = ["Course 1", "Course 2", "Other"]
    
    var body: some View {
        VStack {
            Section {
                Picker(selection: $courseIndex, label: Text("Course")) {
                    ForEach(0 ..< courses.count) {
                        Text(self.courses[$0]).tag($0)
                    }
                }
            }
        
            if courseIndex == 2 {
                Text("Show Extra")
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM