0

It seems that a lot of people just return a UILabel, but in my case I'm adding a label to a view. The view is never not nil. This is a different use of UIPickerView, because I'm rotating its components 90 degrees and having it scroll sideways instead of up and down.

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

    if view == nil {

        let customWidth = 300
        let customHeight = 300

        let view = UIView(frame: CGRect(x:0, y:0, width:customWidth, height:customHeight))

        let label = UILabel(frame:CGRect(x:0, y:0, width:customWidth, height:customHeight))
        if let filter = filters.first(where: {$0.pickerViewRowIndex == row}) {
            var leading = ""
            if appPurchased == false && filter.requiresPurchase == true { leading = "" }
            label.text = "\(leading)\(filter.nameStr)"
        }
        label.textColor = UIColor.black 
        label.font = UIFont(name:"HelveticaNeue-Bold", size: 18.0)
        label.textAlignment = .center

        view.addSubview(label)

        view.transform = CGAffineTransform(rotationAngle: 90 * (.pi/180))
        label.layer.masksToBounds = false

        return view

    }else{
        print("not nil") // console never prints this line
    }

    guard let reusedView = view else {
        assertionFailure("pickerView label view container never set")
        return view!
    }

    return reusedView
}
Chewie The Chorkie
  • 4,896
  • 9
  • 46
  • 90

1 Answers1

2

The view is never not nil.

Correct. The docs are wrong. There is actually no such thing as reusing views in a picker view viewForRow. You always need to make a new view and return it.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Really? I noticed as I scroll it, my CPU % goes up a good 10-15%, probably because it's adding that view continuously over and over. In addition, this seems to pause a timer that is running as I scroll. – Chewie The Chorkie Mar 27 '19 at 16:10
  • 1
    I’m unclear what your comment is saying. I’m just confirming that the console will never print the line you say it never prints, and this is a known fact (bug if you like). – matt Mar 27 '19 at 16:29