Search code examples
swiftuipickerview

UIPickerView: viewForRow not called


I have a problem setting up a UIPickerView. I have set it all up textbook, and I would like to change the font size, but:

  1. Changing the font size via attributedTitleForRow has no effect (although changing the color actually works)

  2. viewForRow never gets called. At all.

I am using Xcode 8 & Swift 2.3 and targeting iOS 8+. Below are all the relevant bits of code:

The Interface Builder (IB) connection:

@IBOutlet weak var synapse: UIPickerView!

The Delegate linked to the UIViewController:

override func viewDidLoad() {
    super.viewDidLoad()

    // Préparation des gestionnaires de transition vers les différentes vues
    self.transitionManagerNav.sourceViewController = self
    self.transitionManagerNav.ordre = "travailleini2barrenav"

    self.transitionManagerDesk.sourceViewController = self
    self.transitionManagerDesk.ordre = "travailleini2desk"

    self.synapse.dataSource = self
    self.synapse.delegate = self

    dateEnCours = graphique.pointDeReference.dateComplete
}

The Delegate implementation:

// UIPICKERVIEWDELEGATE

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return elementsDefileur.count
}

func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
    return 17
}

func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
    return synapse.frame.width
}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}

func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    print("[viewForRow]") // THAT never happens (and yes, I am looking at the correct output window :o)
    let pickerLabel = UILabel()
    pickerLabel.textColor = UIColor.redColor()
    pickerLabel.text = elementsDefileur[row]
    pickerLabel.font = UIFont(name: "Arial-BoldMT", size: 5)
    pickerLabel.textAlignment = NSTextAlignment.Left
    return pickerLabel
}

I have tried all I could think of, including deleting and re creating the UIPickerView from the code and then from (IB), moving the delegate links into viewWillAppear, every combination of titleForRow / attributedTitleForRow / viewForRow, cleaning the project, etc.

How can I fix this problem?


Solution

  • The attribute names in your delegate function declaration are wrong. It should be 'reusingView', not 'reusing view':

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

    I believe the Apple docs contain the error. I had the same problem, and fixed it by fixing the attribute name as above.