In this tutorial, we’ll be customising the UIPickerView properties in our iOS Application. In the previous tutorial, we implemented the UIPickerView class and discussed some of the important helper properties and functions.

在本教程中,我们将在iOS应用程序中自定义UIPickerView属性。 在上一教程中,我们实现了UIPickerView类,并讨论了一些重要的帮助程序属性和功能。

UIPickerView (UIPickerView)

We know that UIPickerView requires the two protocols: UIPickerViewDataSource, UIPickerViewDelegate.

我们知道UIPickerView需要两个协议: UIPickerViewDataSourceUIPickerViewDelegate

Besides the required methods that we had discussed, we can use the following methods to customize the UI of the UIPickerView.

除了我们已经讨论过的必需方法外,我们还可以使用以下方法来自定义UIPickerView的UI。

func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView

Using the above three methods we can override the width and height of the cell, and the view of each cell.

使用以上三种方法,我们可以覆盖单元格的宽度和高度以及每个单元格的视图。

Inside the viewForRow method, we can customize the UILabel by creating our own or just create any random custom view such as a UIImage + UILabel.

viewForRow方法内部,我们可以通过创建自己的UILabel来自定义UILabel,也可以仅创建任意随机的自定义视图,例如UIImage + UILabel。

To change the background color of the UIPickerView simply use the backgroundColor property over the instance.

要更改UIPickerView的背景颜色,只需在实例上使用backgroundColor属性。

In the following section, we’ll first create a UIPickerView with a custom label. Later we’ll add a custom view in place of the custom label.

在以下部分中,我们将首先创建带有自定义标签的UIPickerView。 稍后,我们将添加一个自定义视图来代替自定义标签。

项目情节提要 (Project Storyboard)

We’ve added two UITextField and connected them in the ViewController.swift file.

我们添加了两个UITextField并将它们连接到ViewController.swift文件中。

码 (Code)

The code for the ViewController.swift file is given below:

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

import UIKitclass ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {@IBOutlet weak var textField1: UITextField!@IBOutlet weak var textField2: UITextField!let picker1 = UIPickerView()var arrayOfCountries = ["India","USA","Germany","China", "France","Japan", "Australia", "Greece"]override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.createPickerView()createToolbar()}func createPickerView(){picker1.delegate = selfpicker1.delegate?.pickerView?(picker1, didSelectRow: 0, inComponent: 0)textField1.inputView = picker1textField2.inputView = picker1picker1.backgroundColor = UIColor.brown}func createToolbar(){let toolbar = UIToolbar()toolbar.sizeToFit()toolbar.tintColor = UIColor.redtoolbar.backgroundColor = UIColor.bluelet doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.closePickerView))toolbar.setItems([doneButton], animated: false)toolbar.isUserInteractionEnabled = truetextField1.inputAccessoryView = toolbartextField2.inputAccessoryView = toolbar}@objc func closePickerView(){view.endEditing(true)}func numberOfComponents(in pickerView: UIPickerView) -> Int {return 1}func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {return arrayOfCountries.count}func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{return arrayOfCountries[row]}func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {textField1.text =  arrayOfCountries[row]}func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {return 100.0}func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {return 60.0}func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {var label:UILabelif let v = view as? UILabel{label = v}else{label = UILabel()}label.textColor = UIColor.yellowlabel.textAlignment = .leftlabel.font = UIFont(name: "Helvetica", size: 16)label.text = arrayOfCountries[row]return label}
}

In the viewForRow method, we have set the UILabel color and a system font.
We must update the text here.

viewForRow方法中,我们设置了UILabel颜色和系统字体。
我们必须在这里更新文本。

UIToolbar Tint color is set on the Buttons present in the Toolbar.

UIToolbar淡色在工具栏上的按钮上设置。

The output when the above application was run on a simulator is:

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

In the next section, we’ll create a Dynamic UIPickerView on the second UITextField. We will show a UIImage from the assets in the custom rows.

在下一节中,我们将在第二个UITextField上创建一个Dynamic UIPickerView。 我们将在自定义行中显示资产中的UIImage。

UIPickerView行与UIImage (UIPickerView Row with UIImage)

The code for the updated ViewController.swift file is given below;

更新后的ViewController.swift文件的代码如下:

import UIKitclass ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate {@IBOutlet weak var textField1: UITextField!@IBOutlet weak var textField2: UITextField!let picker1 = UIPickerView()var arrayOfCountries = ["India","USA","Germany","China", "France","Japan", "Australia", "Greece"]var arrayOfColors = ["Red","Orange","Yellow","Green", "Blue","Black"]var activeTextField = 0override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.textField1.delegate = selftextField2.delegate = selfcreatePickerView()createToolbar()}func createPickerView(){picker1.delegate = selfpicker1.delegate?.pickerView?(picker1, didSelectRow: 0, inComponent: 0)textField1.inputView = picker1textField2.inputView = picker1picker1.backgroundColor = UIColor.brown}func createToolbar(){let toolbar = UIToolbar()toolbar.sizeToFit()toolbar.tintColor = UIColor.redtoolbar.backgroundColor = UIColor.bluelet doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.closePickerView))toolbar.setItems([doneButton], animated: false)toolbar.isUserInteractionEnabled = truetextField1.inputAccessoryView = toolbartextField2.inputAccessoryView = toolbar}@objc func closePickerView(){view.endEditing(true)}func numberOfComponents(in pickerView: UIPickerView) -> Int {return 1}func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {switch activeTextField{case 1:return arrayOfCountries.countcase 2:return arrayOfColors.countdefault:return arrayOfColors.count}}func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{switch activeTextField{case 1:return arrayOfCountries[row]case 2:return arrayOfColors[row]default:return arrayOfColors[row]}}func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {switch activeTextField{case 1:textField1.text =  arrayOfCountries[row]breakcase 2:textField2.text = arrayOfColors[row]breakdefault:textField1.text =  arrayOfCountries[row]break}}func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {return 100.0}func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {return 60.0}func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {switch activeTextField{case 1:var label:UILabelif let v = view as? UILabel{label = v}else{label = UILabel()}label.textColor = UIColor.yellowlabel.textAlignment = .leftlabel.font = UIFont(name: "Helvetica", size: 16)label.text = arrayOfCountries[row]return labelcase 2:let parentView = UIView()let label = UILabel(frame: CGRect(x: 60, y: 0, width: 80, height: 50))let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height:50))imageView.image = UIImage(named: "ic_launcher")label.text = arrayOfColors[row]parentView.addSubview(label)parentView.addSubview(imageView)return parentViewdefault:return UILabel()}}func textFieldDidBeginEditing(_ textField: UITextField) {switch textField {case textField1:activeTextField = 1picker1.reloadAllComponents()case textField2:activeTextField = 2picker1.reloadAllComponents()default:activeTextField = 0}}
}

In the above code, we’ve also added TextFieldDelegate Procol in order to detect which UITextField is focused. Based on that we display the relevant UIPickerView with the respective data.

在上面的代码中,我们还添加了TextFieldDelegate Procol,以检测聚焦于哪个UITextField。 基于此,我们将显示相关的UIPickerView和相应的数据。

In the textFieldDidBeginEditing method, we set the activeField Property to 1 or 2 based on the UITextField that is focused.

在textFieldDidBeginEditing方法中,我们根据聚焦的UITextField将activeField属性设置为1或2。

After that we update the UIPickerView by calling reloadAllComponents()

之后,我们通过调用reloadAllComponents()更新UIPickerView。

The output of the above application in action is given below

上面应用程序的输出如下

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

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

iOSCustomPickerViewiOSCustomPickerView

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

自定义iOS UIPickerView相关推荐

  1. VCTransitionsLibrary –自定义iOS交互式转场动画的库

    简介 VCTransitionsLibrary 提供了许多适用于入栈,出栈,模态等场景下控制器切换时的转场动画.它本身提供了一个定义好的转场动画库,你可以拖到自己工程中直接使用;也提供了许多拥有不同转 ...

  2. iOS UIPickerView

    In this tutorial, we'll be discussing UIPickerView component in our iOS Application. 在本教程中,我们将讨论iOS应 ...

  3. iphone控制中心自定义没有计算机,如何在iPhone上自定义iOS 11控制中心功能

    苹果最新推出的适用于iPhone和iPad的iOS 11,具有重新设计和模块化的控制中心.这个新的控制中心具有相当多的3D触摸手势,新的动画和可定制性.此外,内置了新的控件,以前在iOS版本下载或使用 ...

  4. 自定义iOS的状态栏

    有时候,需要在状态栏上显示一些自定义信息,比如新浪微博的官方iOS客户端:告知用户信息处于发送队列.发送成功或者发送失败. 如上图,通过在状态栏显示自定义信息,可以给用户友好又不影响软件使用的提示. ...

  5. 自定义iOS导航栏背景,标题和返回按钮文字颜色-----转载自gyz413977349

    在iOS7下,默认导航栏背景,颜色是这样的,接下来我们就进行自定义,如果你仅仅是更改一下背景和颜色,代码会很简单,不需要很复杂的自定义View来替代leftBarItem 更改导航栏的背景和文字Col ...

  6. 使用图片方式自定义iOS导航栏navigationItem的backBarButtonItem

    2019独角兽企业重金招聘Python工程师标准>>> 在做ViewControlller的navigationItem时,我们经常需要使用自定义的图片来替换系统默认的按钮样式,这点 ...

  7. [原创] CSS自定义IOS苹果,Android安卓的CheckBox 效果,可以根据文字大小变化而变化,内框显示文字,另外可自定大小,自定颜色...

    在经过对网上一些自定CheckBox的一番研究之后,现在综合讲一下该样式实现的技巧. 先上图: 图中已展示了多种样式,实现的原理很简单,一个外Box,一个内Box,外Box显示背景色,内Box显示白色 ...

  8. ios UIPickerView 技巧集锦

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

  9. 自定义IOS系统弹框

    写在之前 系统的弹框虽然很好看,但是有时候无法完全满足UI设计的需求,比如说中间要显示一个输入框,或者要放置一张图片,这里介绍一个很早之前的自定义弹框库,这个自定义弹框sdk写的很细致,定制性很强,几 ...

最新文章

  1. weblogic 修改控制台密码
  2. log4j用法http://zengjinliang.javaeye.com/blog/171550
  3. 程序出错后,程序员给测试人员的20条高频回复
  4. oracle简版如何打开,如何打开和关闭Oracle游标
  5. 洛谷——P1101 单词方阵
  6. mysql表空间被占用,同名表无法创建或导入
  7. python求函数极值_python 遗传算法求函数极值的实现代码
  8. Django create_user with is_active=False
  9. 【图像处理基础知识(python+openCV)】——目标检测
  10. JAVA基础系列:Arrays.binarySearch二分查找
  11. 普通人有必要学新媒体吗?
  12. 一作解读NLPCC最佳学生论文:1200万中文对话数据和预训练模型CDial-GPT
  13. Maven常用插件配置和使用
  14. 2019腾讯校招客户端方向面经(已拿offer)
  15. 强化学习--蒙特卡洛法
  16. 获取html中光标位置
  17. centos怎么读(centos系统怎么读)
  18. Cg学习记录002 之Uniform参数
  19. 【会声会影】视频导出、输出时,如何设置参数
  20. 关于点进Steam页面白屏解决办法

热门文章

  1. 浏览器控制台console
  2. POJ 1325 Machine Schedule(zoj 1364) 最小覆盖数
  3. 资源重复 uac.res resource kept(转)
  4. Windows Mobile开发的一些小技巧(持续更新)
  5. [概率][lca][dfs][树形dp] Jzoj P4225 宝藏
  6. 正则表达式的几个简单验证
  7. 在数组中寻找出现次数超过数组长度一半的数
  8. Codeforces Round #301 (Div. 2) B. School Marks 构造/贪心
  9. 简单的二维数组问题,不用不知道,一用吓一跳
  10. 自动化登陆博客园脚本