Following on from my recent post about implementing UIPickerViews, this post looks at creating a custom item renderer for the same control.
The UIPickerView in my demonstration displays a list of colours, so it would be nice if rather than simply displaying the name of the colour, it also displayed a little preview swatch.
To do this, we need to create another custom component which extends UIControl. My component is called ColorSpinnerItemRenderer and its init() method requires an argument of type NamedColor.
The ColorSpinnerItemRenderer contains three sub-components, a label, a UIView which acts as a border and a UIView which acts as the swatch. Inside the init(), I populate the label with the colour's name and set the swatch's backgroundColor to the color's UIColor:
init(frame : CGRect, color : NamedColor)
{
super.init(frame: CGRect(x: 0, y: 0, width: 200, height: 80))
label.text = color.name
border.backgroundColor = UIColor.whiteColor()
swatch.backgroundColor = color.color
addSubview(label)
addSubview(border)
addSubview(swatch)
}
Theres's some pixel tweaking in the renderer's didMoveToView to layout the components:
overridefunc didMoveToWindow()
{
label.frame = CGRect(x: 20, y: 0, width: 200, height: 80)
border.frame = CGRect(x: 158, y: 80 / 2 - 7, width: 34, height: 14)
swatch.frame = CGRect(x: 160, y: 80 / 2 - 5, width: 30, height: 10)
}
Setting the new component as the spinner lists's item renderer couldn't be simpler. One of the optional methods inside UIPickerViewDelegate allows the definition of the renderer:
optionalfunc pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView
...so by implementing that and passing the current colour into the renderer, we can see it in action:
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView
{
returnColorSpinnerItemRenderer(frame: CGRectZero, color : colors[row])
}
As always, all of the source code is available in my GitHub repository.