user3069232 user3069232 - 1 month ago 25
Swift Question

PickerView UI bug in iOS 10.x

iOS 10.0.2 Swift 3.0

Cut'n'Pasted a basic code needed in a ViewController for a UIPickerView ... see the two comments. Is a bug in the compiler?

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate ,UIPickerViewDataSource {

var pickerView:UIPickerView = UIPickerView()
var blah: Array = ["1","2","3","4"]

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.pickerView.delegate = self
self.pickerView.dataSource = self

works //pickerView.frame = CGRect(x: 100, y: 100, width: 100, height: 162)
broken // pickerView = UIPickerView(frame: CGRect(x: 100, y: 100, width: 100, height: 162))

view.addSubview(pickerView)
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

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

// The number of rows of data
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return blah.count
}

// The data to return for the row and component (column) that's being passed in
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return blah[row]
}

// Catpure the picker view selection
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// This method is triggered whenever the user makes a change to the picker selection.
// The parameter named row and component represents what was selected.
}


}

Answer

As @Larme said in his comment, you are redeclaring the pickerView. The delegate and dataSource for the pickerView must be set after it has been initialised.

So you should use either:

var pickerView = UIPickerView()

override func viewDidLoad() {
    super.viewDidLoad()

    self.pickerView.delegate = self
    self.pickerView.dataSource = self

    pickerView.frame = CGRect(x: 100, y: 100, width: 100, height: 162)

    view.addSubview(pickerView)
}

Or:

var pickerView: UIPickerView!

override func viewDidLoad() {
    super.viewDidLoad()

    pickerView = UIPickerView(frame: CGRect(x: 100, y: 100, width: 100, height: 162))

    pickerView.delegate = self
    pickerView.dataSource = self

    view.addSubview(pickerView)
}