UIPickerView and Swift 3: How to make Protocols and Conform People

UIPickerView and Swift 3

I’ve been learning how to code using Swift 3. As Swift 3 is still so new, a lot of the help on the Tinterweb is for Swift 2. When you try to get help with the Cocoa and Interface Builder stuff things can get a little tricky. What the net says works perfectly in Swift 2 will not always work in Swift 3 because things have been renamed and so on. I hit this problem with trying to get a UIPickerView working in an iOS app I was building.

No matter what I did I couldn’t get Xcode to stop complaining that my View Controller class did not conform to the UIPickerViewDataSource protocol. Xcode was happy that I had conformed to UIPickerViewDelegate, but despite implementing the methods, and responding to Xcode’s error and fix reports, I still couldn’t get rid of the red error triangle for UIPickerViewDataSource.

So, if you ever have this problem here is the code I used to get it to eventually work.

class MyViewController: UIViewController, UIPickerViewDelegate, UIPickerVIewDataSource
let mySource = ["Option 1", "Option 2", "Option 3"]

override func viewDidLoad()
// Do any additional setup after loading the view.
myPicker.dataSource = self
myPicker.delegate = self

// MARK: IB Outlets
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var myPicker: UIPickerView!

//MARK: - Delegates and data sources
//MARK: Data Sources
func numberOfComponents(in pickerView: UIPickerView) -> Int
return 1

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
return mySource.count

//MARK: Delegates
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
return mySource[row]

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
myLabel.text = mySource[row]

It seems that the above had the correct combination of methods, labels, arguments, parameters, brackets, parentheses, stupid squiggly braces that are an abomination and should be banned, and all round general awesomeness.

Thanks, Tinterweb 🙂

Leave a Reply

%d bloggers like this: