在 SwiftUI 中,Picker 是一个非常常用的组件,用于选择多个选项中的一个(例如下拉菜单或滚轮选择器)。它支持文本、图像、复合视图等作为选项。
基本用法
单选 Picker 示例
import SwiftUI
struct ContentView: View {
@State private var selectedOption = "Apple" // 默认选中值
let options = ["Apple", "Banana", "Cherry"]
var body: some View {
VStack {
Text("Selected: \(selectedOption)")
Picker("Select a fruit", selection: $selectedOption) {
ForEach(options, id: \.self) { option in
Text(option).tag(option) // 设置标识符
}
}
.pickerStyle(.wheel) // 可选:选择样式
}
.padding()
}
}

Picker 样式
SwiftUI 提供了多种 Picker 样式:
.automatic:自动选择样式(默认行为)

.inline:内联选择器样式

.menu:下拉菜单样式(适用于 iOS 和 macOS)

.navigationLink:单行选项


需要注意的是,需要配合NavigationStack才能使用. navigationLink选项。
. palette:选项以水平或网格布局显示。

.segmented:分段选择器(类似 UISegmentedControl)

.wheel:滚轮选择器(适用于 iOS)

提示
部分样式(如 .palette)可能需要特定平台支持,例如在 Apple Watch 上更常见。如果在 iOS 中使用这些样式,需要注意平台差异和用户体验设计。