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需要两个协议: UIPickerViewDataSource
和UIPickerViewDelegate
。
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。 稍后,我们将添加一个自定义视图来代替自定义标签。