PickerView

17 Mar 2025 | 5 分钟阅读

PickerView 可以定义为一个显示旋转轮或老虎机以显示一个或多个值集合的视图,以便用户可以旋转轮盘选择一个。它是 UIPickerView 类的实例,继承自 UIView。

顾名思义,选择器视图允许用户从多个项目的集合中选择一个项目。 PickerView 可以显示一个或多个集合,其中每个集合称为一个组件。每个组件显示一系列索引行,代表可选择的项目。用户可以通过旋转轮盘来选择项目。

将 PickerView 添加到 iOS 应用程序

  • 在对象库中搜索 UIPickerView,然后将结果拖到故事板中。
  • 为选择器视图定义自动布局规则,以控制其在不同屏幕设备上的位置和大小。
  • 实现 UIPickerViewDelegate 和 UIPickerViewDataSource 协议,以控制 PickerView 的数据和外观。

UIPickerView 方法

序号方法描述
1func numberOfRows(inComponent: Int) -> Int它表示在选择器视图的单个组件中显示的行数。
2func rowSize(forComponent: Int) -> CGSize它表示 iOS 应用程序中指定组件的行大小。
3func reloadAllComponents()此函数用于重新加载选择器视图的所有组件。
4func reloadComponent(Int)此函数用于重新加载选择器视图的特定组件。
5func selectRow(Int, inComponent: Int, animated: Bool)此方法用于在特定选择器视图的指定组件中选择一行。
6func selectedRow(inComponent: Int) -> Int此方法用于返回选择器视图中所选行的指定组件的索引。
7func view(forRow: Int, forComponent: Int) -> UIView?此方法用于返回选择器视图用于给定行和组件的视图。

UIPickerView 属性

序号属性描述
1var dataSource: UIPickerViewDataSource?它表示指定选择器视图的数据源。
2var delegate: UIPickerViewDelegate?它表示选择器视图的委托。
3var numberOfComponents: Int它表示选择器视图中的组件数量。

UIPickerViewDataSource

UIPickerViewDataSource 用于为选择器视图提供组件数量以及每个组件中的行数,以显示选择器视图数据。

序号方法描述
1func numberOfComponents(in: UIPickerView) -> Int它表示一个整数,表示 iOS 中选择器视图中的组件数量。
2func pickerView(UIPickerView, numberOfRowsInComponent: Int) -> Int它表示一个整数,表示特定应用程序中的行数。

UIPickerViewDelegate

UIPickerViewDelegate 的对象必须符合 UIPickerViewDelegate 协议,以定义每个组件中行的 height、width、row title 和 view content。

序号方法描述
1func pickerView(UIPickerView, rowHeightForComponent: Int) -> CGFloat当选择器视图需要设置选择器视图组件中某行的高度时,会调用此方法。
2func pickerView(UIPickerView, widthForComponent: Int) -> CGFloat当选择器视图需要设置选择器视图组件中某行的宽度时,会调用此方法。
3func pickerView(UIPickerView, titleForRow: Int, forComponent: Int) -> String?它返回一个字符串,表示选择器视图组件中该行的标题。
4func pickerView(UIPickerView, attributedTitleForRow: Int, forComponent: Int) -> NSAttributedString?当选择器视图需要设置选择器视图组件中任何行的样式标题时,会调用此方法。
5func pickerView(UIPickerView, viewForRow: Int, forComponent: Int, reusing: UIView?) -> UIView它返回一个 UIView 对象,用于指定组件中的指定行。
6func pickerView(UIPickerView, didSelectRow: Int, inComponent: Int)当用户在选择器视图组件中选择一行时,会调用此方法。

示例

这是一个非常简单的示例,我们将在其中将选择器视图添加到我们的界面中。我们将定义数据源和委托方法来设置选择器视图的数据和外观。

界面生成器

要为此示例创建界面生成器,我们将搜索选择器视图,如下面的图像所示。

iOS PickerView

用于此项目的完整 main.storyboard 如下面的图像所示,其中,我们使用了标签和选择器视图来选择项目。

iOS PickerView

ViewController.swift

输出

iOS PickerView

示例 2

在此示例中,我们将了解选择器视图的正确功能。在这里,我们创建了标签,然后是选择器视图。每个标签都与特定组件关联。

Main.storyboard

在此示例中,我们提示用户从选择器视图中选择时间。在这里,我们将创建单独的组件和标签来显示小时、分钟和秒。我们将更改标签的文本,以从选择器视图中选择适当的值。

iOS PickerView

ViewController.swift

输出

iOS PickerView
下一主题ProgressView