【问题标题】:App to expand 'Other' category when selected on picker from a form (SwiftUI))应用程序在从表单(SwiftUI)的选择器上选择时扩展“其他”类别)
【发布时间】:2020-09-23 23:19:35
【问题描述】:

我想为用户提供一个类别列表(通过表单中包含的选择器),最后列出的类别是“其他”。如果用户选择“其他”,应用程序将在表单中添加一个字段供用户输入新的类别名称(将保存以供将来参考)。

我已经能够显示选择器列表:

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

但我无法确定如何显示新字段以供用户输入新类别。

谢谢。

【问题讨论】:

  • 您可以使用.onChange(of: VAR),如果选择了其他,请为新部分启用标志,但可能有更好的方法

标签: swift forms swiftui picker


【解决方案1】:

您可以在 BodyBuilder 中添加使用if,例如:

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")
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2019-07-14
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多