3.9_如何创建Picker并从中读取值

1. 简介

SwiftUI 中的 Picker 视图可以将 UIPickerUITableView 结合在一起。同时还可以适应其它操作系统上的其它样式。很好的一点是,我们真的不需要关心它的工作原理 – SwiftUI 在自动适应环境方面做得很好。

与大多数其它控件一样,我们必须将 Picker 附加到某种状态属性,以跟踪 picker 的选择。

2. 示例

例如: 我们将创建一个 colors 数组和一个存储所选颜色的整数,然后将其与 Picker,Text 视图一起使用,以便我们可以看到正在读取的值:

struct ContentView: View {
    
    var colors = ["Red", "Green", "Blue", "Tartan"]
    @State private var selectedColor = 0
    
    var body: some View {
        VStack {
            Picker(selection: $selectedColor, label: Text("Please choose a color")) {
                ForEach(0..<colors.count) {
                    Text(self.colors[$0])
                }
            }
            Text("You selected: \(colors[selectedColor])")
        }
    }
}

效果预览: 3.9_picker_select_color

Avatar
M X
Mobile, Front-End Developer

My research interests include swift developing, python developing and go developing.

Related

Next
Previous
comments powered by Disqus