Search code examples
iosswiftuipickerview

UIPickerView reusing view is always nil


According to Apples API references reusing view in this method

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

is a cached view by picker view but when I'm trying to use it for next rows it's always nil while I'm returning a UILabel when reusing view is nil. What is the problem? this is my implementation:

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    let pickerLabel = UILabel()
    pickerLabel.textColor = UIColor.black
    pickerLabel.text = "10"
    pickerLabel.textAlignment = NSTextAlignment.center
    pickerLabel.sizeToFit()
    return pickerLabel
}

Solution

  • Your code makes no attempt to use the reuse view. Your code should be something like this:

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        var pickerLabel : UILabel
        if let label = view as? UILabel {
            pickerLabel = label
        } else {
            pickerLabel = UILabel()
            pickerLabel.textColor = UIColor.black
            pickerLabel.textAlignment = NSTextAlignment.center
        }
    
        pickerLabel.text = "10"
        pickerLabel.sizeToFit()
    
        return pickerLabel
    }
    

    This code reuses the label if the reuse view is a label. Otherwise it creates and sets up a new label.

    Note that a picker will only pass in a reuse view as the picker view is scrolled. It's similar to a table view's cell reuse.