In this tutorial, we’ll be discussing UIPickerView component in our iOS Application.

在本教程中,我们将讨论iOS应用程序中的UIPickerView组件。

UIPickerView (UIPickerView)

UIPickerView is a UI element which is used to make a selection from multiple choices displayed in a vertical wheel. It is quite similar to what a dropdown is in Android or Web UI.

UIPickerView是一个UI元素,用于从垂直轮中显示的多个选项中进行选择。 它与Android或Web UI中的下拉菜单非常相似。

A wheel is known as a component in a UIPickerView.
A single UIPickerView can host one or more components.
Every component can contain independent data and can be selected and changed.
Typically, an array is used to display data in the rows of a UIPickerView component.

车轮在UIPickerView中被称为组件
一个UIPickerView可以托管一个或多个组件。
每个组件都可以包含独立的数据,并且可以选择和更改。
通常,数组用于在UIPickerView组件的行中显示数据。

To show data in the UIPickerView you must adopt the protocol, UIPickerViewDataSource in your application and implement its required methods.
You must adopt the protocol, UIPickerViewDelegate in order to display the rows and also to allow making user selections.

要在UIPickerView中显示数据,您必须在应用程序中采用协议UIPickerViewDataSource并实现其必需的方法。
您必须采用协议UIPickerViewDelegate才能显示行并允许用户进行选择。

If you don’t use the latter protocol in your ViewController, you might end up with something like this :

如果您在ViewController中不使用后一个协议,则可能会得到如下所示的结果:

Following are the four most important functions:

以下是四个最重要的功能:

func numberOfComponents(in pickerView: UIPickerView) -> Int
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
  • titleForRow is used to display the data in the UIPickerView component(s).titleForRow用于在UIPickerView组件中显示数据。
  • didSelectRow gets called whenever any of the UIPickerView rows is selected.每当选择任何UIPickerView行时,就会调用didSelectRow

Before we get down to the complex stuff in a later section, let’s implement a simple UIPicker in our XCode Single View Application Project.

在下一节中介绍复杂的内容之前,让我们在XCode Single View Application Project中实现一个简单的UIPicker。

项目情节提要 (Project Storyboard)

We’ve added a UIPickerView, a UILabel and a UITextField. We’ll display the selection from the UIPickerView in the UILabel. Later we’ll create another UIPickerView at the bottom to choose the text for the UITextField.

我们添加了一个UIPickerView,一个UILabel和一个UITextField。 我们将在UILabel中的UIPickerView中显示选择。 稍后,我们将在底部创建另一个UIPickerView来选择UITextField的文本。

码 (Code)

The code for the ViewController.swift is given below:

下面给出了ViewController.swift的代码:

import UIKitclass ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {@IBOutlet weak var myTextField: UITextField!@IBOutlet weak var myLabel: UILabel!@IBOutlet weak var topPickerView: UIPickerView!var arrayOf100 = Array(0...100)var arrayOf2 = Array(1...2)var labelString = ""override func viewDidLoad() {super.viewDidLoad()topPickerView.delegate = selftopPickerView.delegate?.pickerView?(topPickerView, didSelectRow: 0, inComponent: 0)topPickerView.delegate?.pickerView?(topPickerView, didSelectRow: 0, inComponent: 1)}func numberOfComponents(in pickerView: UIPickerView) -> Int {return 2}func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {if component == 0{return arrayOf2.count}else{return arrayOf100.count}}func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{if component == 0 {return String(arrayOf2[row])}else{return String(arrayOf100[row])}}func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {let digitsValue = arrayOf2[topPickerView.selectedRow(inComponent: 0)]let decimalValue = arrayOf100[topPickerView.selectedRow(inComponent: 1)]myLabel.text = "Value is \(digitsValue).\(decimalValue)"if component == 0 {print(String(arrayOf2[row]))}else{print(String(arrayOf100[row]))}}
}

topPickerView.delegate = self is the most important line. In a way it activates the Protocols on the UIPickerView instance.

topPickerView.delegate = self是最重要的行。 它以某种方式在UIPickerView实例上激活协议。

We’re returning 2 components and we’ve populated each of them with a different array.

我们将返回2个组件,并为每个组件填充一个不同的数组。

didSelectRow gets called whenever any of the rows are selected. BUT, it won’t call all of the components in the selection. For that, we use the selectedRow(inComponent:) to get the values from the selected rows of the components. These are then appended and displayed in a string.

每当选择任何行时,就会调用didSelectRow 。 但是,它不会调用选择中的所有组件。 为此,我们使用selectedRow(inComponent:)从组件的选定行中获取值。 然后将它们附加并显示在字符串中。

Since the initial state doesn’t trigger didSelectRow, we call the method on both of our components in the viewDidLoad method.

由于初始状态不会触发didSelectRow ,因此我们在viewDidLoad方法的两个组件上都调用了该方法。

The output when the above application was run on the iOS Simulator is:

在iOS模拟器上运行上述应用程序时的输出为:

Now let’s create another UIPickerView which would open instead of the Keyboard.

现在让我们创建另一个UIPickerView,它将代替键盘打开。

UIPickerView代替键盘 (UIPickerView in place of Keyboard)

To add a UIPickerView in place of keyboard we just need to set the inputView property on the UITextField to the UIPickerView.

要添加UIPickerView代替键盘,我们只需要将UITextField的inputView属性设置为UIPickerView。

func createAnotherPicker(){let anotherPicker = UIPickerView()anotherPicker.delegate = selfanotherPicker.delegate?.pickerView?(anotherPicker, didSelectRow: 0, inComponent: 0)myTextField.inputView = anotherPicker}

Following is the updated code of the ViewController.swift. All we need to do in the delegate methods is to check for the type of the UIPickerView instance in order to use both the UIPickerViews

以下是ViewController.swift的更新代码。 在委托方法中,我们要做的就是检查UIPickerView实例的类型,以便同时使用两个UIPickerViews。

import UIKitclass ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {@IBOutlet weak var myTextField: UITextField!@IBOutlet weak var myLabel: UILabel!@IBOutlet weak var topPickerView: UIPickerView!var arrayOf100 = Array(0...100)var arrayOf2 = Array(1...2)var labelString = ""let anotherPicker = UIPickerView()var arrayOfCountries = ["India","USA","Germany","China", "France","Japan", "Australia", "Greece"]override func viewDidLoad() {super.viewDidLoad()topPickerView.delegate = selftopPickerView.delegate?.pickerView?(topPickerView, didSelectRow: 0, inComponent: 0)topPickerView.delegate?.pickerView?(topPickerView, didSelectRow: 0, inComponent: 1)createAnotherPicker()}func createAnotherPicker(){anotherPicker.delegate = selfanotherPicker.delegate?.pickerView?(anotherPicker, didSelectRow: 0, inComponent: 0)myTextField.inputView = anotherPicker}func numberOfComponents(in pickerView: UIPickerView) -> Int {if pickerView == topPickerView{return 2}else{return 1}}func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {if pickerView == topPickerView{if component == 0{return arrayOf2.count}else{return arrayOf100.count}}else{return arrayOfCountries.count}}func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{if pickerView == topPickerView{if component == 0 {return String(arrayOf2[row])}else{return String(arrayOf100[row])}}else{return arrayOfCountries[row]}}func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {if pickerView == topPickerView{let digitsValue = arrayOf2[topPickerView.selectedRow(inComponent: 0)]let decimalValue = arrayOf100[topPickerView.selectedRow(inComponent: 1)]myLabel.text = "Value is \(digitsValue).\(decimalValue)"if component == 0 {print(String(arrayOf2[row]))}else{print(String(arrayOf100[row]))}}else{myTextField.text =  arrayOfCountries[row]}}
}

The output of the above-updated application in action is :

上面更新的实际应用程序的输出为:

In order to dismiss the UIPickerView, we can set the touchesBegan method with view.endEditing(true).

为了消除UIPickerView,我们可以使用view.endEditing(true)设置touchesBegan方法。

An even better option is to add a UIToolbar with a dismiss button on the UIPickerView.

更好的选择是在UIPickerView上添加带有关闭按钮的UIToolbar。

UIPickerView和UIToolbar (UIPickerView with UIToolbar)

Add the following function in your ViewController.swift file

在ViewController.swift文件中添加以下函数

func createToolbar(){let toolbar = UIToolbar()toolbar.sizeToFit()let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.closePickerView))toolbar.setItems([doneButton], animated: false)toolbar.isUserInteractionEnabled = truemyTextField.inputAccessoryView = toolbar}

We’ve added a Button in the UIToolBar and set the Toolbar as the inputAccessoryView. That means it would be shown above the UIPickerView when the UITextField is clicked.

我们在UIToolBar中添加了一个Button并将Toolbar设置为inputAccessoryView。 这意味着当单击UITextField时,它将显示在UIPickerView上方。

When the Done button is clicked, the following method would get executed:

单击“完成”按钮时,将执行以下方法:

@objc func closePickerView(){view.endEditing(true)}

This will close the input view.

这将关闭输入视图。

Don’t forget to add the method createToolbar() in your viewDidLoad method.

不要忘记在viewDidLoad方法中添加方法createToolbar()。

The output of the application in action is:

实际应用程序的输出为:

This brings an end to this tutorial. You can download the project from the link below:

本教程到此结束。 您可以从下面的链接下载项目:

iOSUIPickerViewiOSUIPickerView

翻译自: https://www.journaldev.com/22731/ios-uipickerview

iOS UIPickerView相关推荐

  1. 自定义iOS UIPickerView

    In this tutorial, we'll be customising the UIPickerView properties in our iOS Application. In the pr ...

  2. ios UIPickerView 技巧集锦

    重新实现 UIPickerView 参考资料: http://www.cocoachina.com/bbs/read.php?tid=85374 http://www.cocoachina.com/i ...

  3. 【iOS开发每日小笔记(一)】UIPickerView 自动选择某个component的某个row

    这篇文章是我的[iOS开发每日小笔记]系列中的一片,记录的是今天在开发工作中遇到的,可以用很短的文章或很小的demo演示解释出来的小心得小技巧.它们可能会给用户体验.代码效率得到一些提升,或是之前自己 ...

  4. 【iOS开发】-UIPickerView

    写在开头 昨天学习了iOS一个简单的控件. UIPickerView; UIPickerView组件类似HTML都Select组件效果,提供数据供用户选择.可以通过plist文件提供数据.UIPick ...

  5. iOS :UIPickerView reloadAllComponets not work

    编辑信息页面用了很多选择栏,大部分都用 UIPickerView 来实现.在切换数据显示的时候, UIPickerView 不更新数据,不得其解.Google 无解,原因在于无法描述自己的问题,想想应 ...

  6. 【IOS 开发】基本 UI 控件详解 (UIDatePicker | UIPickerView | UIStepper | UIWebView | UIToolBar )

    转载注明出处 : http://blog.csdn.net/shulianghan/article/details/50348982 一. 日期选择器 (UIDatePicker) UIDatePic ...

  7. timerpickerview使用_详解iOS App中UIPickerView滚动选择栏的添加方法

    1.UIPickerView的宽度和高度是固定的,纵向是320216,横向是568162 2.属性: @property(nonatomic,readonly)NSInteger numberOfCo ...

  8. UIPickerView 选取器(滚轮)—IOS开发

    选取器被用来取代PC上面的下拉菜单,它是一个大大的滚轮,它占用固定的大小 320×216. 一.创建 大小虽然固定,但是位置可以任意(不过横向被充满,咱也只能改变纵向位置).与UItableView ...

  9. IOS的UIPickerView 和UIDatePicker

    1.UIPickerView的常见属性 1 //数据源(用来告诉UIPickerView有多少列多少行) 2 @property(nonatomic,assign) id<UIPikerView ...

最新文章

  1. 现在可以插入MSN表情了
  2. easyexcel模板循环模板怎么循环_雅思大作文怎么熟练套模板
  3. Curses 中的 noecho() 函数
  4. 操作系统内存管理--简单、页式、段式、段页式
  5. java中有关线程的题目
  6. 万能电商Banner素材模板,一切产品为王
  7. 一起来学jquery!
  8. 华为防火墙USG6320透明模式配置
  9. 学习 nltk —— TF-IDF
  10. 华为交换机 查ip冲突_华为交换机:如何解决网络中IP地址发生冲突故障?
  11. 信号检测与估计(1)
  12. 苹果蓝牙耳机平替哪个好用?商务通话蓝牙耳机推荐
  13. SDOI2015寻宝游戏
  14. 简单高效的图片降噪方法
  15. layim之邀请好友加入群组
  16. extern 用法详解
  17. js计算时间差,包括计算,天,时,分,秒
  18. AcWing 487. 金明的预算方案
  19. 机器人或将人类推向“无能之下的自由”
  20. c语言中什么叫喂狗,STM32是怎么初始化看门狗和喂狗的

热门文章

  1. 每天CookBook之JavaScript-032
  2. UVALive 4212 Candy
  3. SQL Server 2005 正则表达式使模式匹配和数据提取变得更容易
  4. 傅里叶变换的终极解释下
  5. [转载] 递归函数python基例_python递归函数详解 python 递归函数使用装饰器
  6. [转载] 1006- Python 字典(Dictionary) items()方法
  7. 接口jdk1.8与jdk1.9新特性
  8. PyQt5-QTextEdit控件使用
  9. day17 Python 反射获取内容和修改内容
  10. sql 查询的在northern最大的价值(LAT_N),小于137.2345 ,在小数点后4 位截断