SwiftUI 表单中的 4 种Picker选择器样式

Picker是用于从选项列表中选择值的控件。

Picker在 a 中使用时Form选择器样式会根据平台和版本自动更改。

在本文中,我们将探讨所有可能的选择器样式,以便您可以选择适合您需要的样式。

默认选择器样式

如果您不指定选择器样式,SwiftUI 将根据平台和版本选择一个。

在 iOS 16 中,选择器将使用menu样式。

当用户点击选择器时,该menu样式会将选项显示为弹出菜单。

struct ContentView: View {
@State private var selectedTheme = "Dark"
let themes = ["Dark", "Light", "Automatic"]

var body: some View {
NavigationStack {
Form {
Section {
Picker("Appearance", selection: $selectedTheme) {
ForEach(themes, id: \.self) {
Text($0)
}
}
}
}
.navigationTitle("Display & Brightness")
}
}
}
iOS 16 中的默认选择器样式。
iOS 16 中的默认选择器样式。

在未来的 iOS 版本中,默认样式可能会发生变化。

如果你想使用这种风格,你可以明确指定.pickerStyle(.menu)一个选择器视图。

Picker("Appearance", selection: $selectedTheme) {
ForEach(themes, id: \.self) {
Text($0)
}
}
.pickerStyle(.menu)

如果您有一长串选项并且想要将选项选择放到另一个视图中navigationLink,您可以通过应用选择器样式来实现。

这是您在 Apple 设置应用程序中看到的样式。

struct ContentView: View {
@State private var selectedTheme = "Dark"
let themes = ["Dark", "Light", "Automatic"]

var body: some View {
NavigationStack {
Form {
Picker("Appearance", selection: $selectedTheme) {
ForEach(themes, id: \.self) {
Text($0)
}
}
.pickerStyle(.navigationLink)
}
.navigationTitle("Display & Brightness")
}
}
}

选择器就像一个导航链接,将用户推送到另一个带有选项列表的视图。

.pickerStyle(.navigationLink)
.pickerStyle(.navigationLink)

内联选择器样式

如果您只有几个选择,inline风格可能是一个不错的选择。

它将每个选项与表单中的其他控件放在一起。使用此样式,您只需轻按一下即可选择一个选项。

struct ContentView: View {
@State private var selectedTheme = "Dark"
let themes = ["Dark", "Light", "Automatic"]

var body: some View {
NavigationStack {
Form {
Picker("Appearance", selection: $selectedTheme) {
ForEach(themes, id: \.self) {
Text($0)
}
}
.pickerStyle(.inline)
Toggle("Bold Text", isOn: .constant(true))
}
.navigationTitle("Display & Brightness")
}
}
}

我还添加了一个Toggle控件来演示选择器如何与其他控件一起布局。

.pickerStyle(.内联)
.pickerStyle(.内联)

轮式拾取器样式

滚轮选择器样式将在可滚动的滚轮中显示选项。

此样式还将选项与表单中的其他控件内嵌在一起,但外观类似轮子

下面是轮子的一些行为。

  • 无论选项如何,它都有一个固定的高度。
  • 只有有限数量的选项是可见的
struct ContentView: View {
@State private var selectedTheme = "Dark"
let themes = ["Dark", "Light", "Automatic"]

var body: some View {
NavigationStack {
Form {
Picker("Appearance", selection: $selectedTheme) {
ForEach(themes, id: \.self) {
Text($0)
}
}
.pickerStyle(.wheel)
Toggle("Bold Text", isOn: .constant(true))
}
.navigationTitle("Display & Brightness")
}
}
}
.pickerStyle(.wheel)
.pickerStyle(.wheel)

分段选择器样式

最后一种样式是,其中每个选项都以类似选项卡的样式segmented呈现。

struct ContentView: View {
@State private var selectedTheme = "Dark"
let themes = ["Dark", "Light", "Automatic"]

var body: some View {
NavigationStack {
Form {
Picker("Appearance", selection: $selectedTheme) {
ForEach(themes, id: \.self) {
Text($0)
}
}
.pickerStyle(.segmented)
Toggle("Bold Text", isOn: .constant(true))
}
.navigationTitle("Display & Brightness")
}
}
}

所有选项都在同一行水平对齐,因此它仅适用于只有少数选项的选择器。

.pickerStyle(.segmented)
.pickerStyle(.segmented)

结论

尽管标题说的是 SwiftUI Form 中的选择器样式,但您可以在任何需要的地方使用这些样式。

唯一的区别是外观可能不一样,因为 SwiftUI Form 将自定义样式应用于其子视图。

庄朋龙
庄朋龙

一个爱生活的技术菜鸟

留下评论

您的电子邮箱地址不会被公开。 必填项已用*标注