自定义iOS UIPickerView

该教程详细介绍了如何在iOS应用中自定义UIPickerView,包括设置UILabel颜色、字体,以及在自定义行中添加UIImage。通过实现相关协议和方法,可以调整UIPickerView的外观和行为,如修改单元格的宽度、高度和背景颜色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 UIKit

class 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 = self
        picker1.delegate?.pickerView?(picker1, didSelectRow: 0, inComponent: 0)
        textField1.inputView = picker1
        textField2.inputView = picker1
        picker1.backgroundColor = UIColor.brown
        
    }
  

    
    func createToolbar()
    {
        let toolbar = UIToolbar()
        toolbar.sizeToFit()
        toolbar.tintColor = UIColor.red
        toolbar.backgroundColor = UIColor.blue
        let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.closePickerView))
        toolbar.setItems([doneButton], animated: false)
        toolbar.isUserInteractionEnabled = true
        textField1.inputAccessoryView = toolbar
        textField2.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:UILabel
        
        if let v = view as? UILabel{
            label = v
        }
        else{
            label = UILabel()
        }
        
        label.textColor = UIColor.yellow
        label.textAlignment = .left
        label.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 UIKit

class 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 = 0
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        textField1.delegate = self
        textField2.delegate = self
        createPickerView()
        createToolbar()
    }
    
    func createPickerView()
    {
        picker1.delegate = self
        picker1.delegate?.pickerView?(picker1, didSelectRow: 0, inComponent: 0)
        textField1.inputView = picker1
        textField2.inputView = picker1
        picker1.backgroundColor = UIColor.brown
    }
  

    
    func createToolbar()
    {
        let toolbar = UIToolbar()
        toolbar.sizeToFit()
        toolbar.tintColor = UIColor.red
        toolbar.backgroundColor = UIColor.blue
        let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.closePickerView))
        toolbar.setItems([doneButton], animated: false)
        toolbar.isUserInteractionEnabled = true
        textField1.inputAccessoryView = toolbar
        textField2.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.count
        case 2:
            return arrayOfColors.count
        default:
            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]
            break
            
        case 2:
            textField2.text = arrayOfColors[row]
            break

        default:
            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:UILabel
        
        if let v = view as? UILabel{
            label = v
        }
        else{
            label = UILabel()
        }
        
        label.textColor = UIColor.yellow
        label.textAlignment = .left
        label.font = UIFont(name: "Helvetica", size: 16)
        
        label.text = arrayOfCountries[row]
        
        return label
         
        case 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 parentView
            
        default:
            return UILabel()
            
        }
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        
        switch textField {
        case textField1:
            activeTextField = 1
            picker1.reloadAllComponents()
        case textField2:
            activeTextField = 2
            picker1.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:

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值