简体   繁体   中英

Does not conform to protocol UIPickerViewDataSource

I don't know what's wrong with my code. I tried to follow the tutorial but same error happen.

Error:

Type 'FourthViewController' does not conform to protocol 'UIPickerViewDataSource'

Here is my code:

import UIKit

let characters = ["Jaja Bink", "Luke", "Han Solo", "Princess Leia"];

let weapons = ["LightSaber", "Pistol", "Keris"];

class FourthViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    @IBOutlet weak var doublePicker: UIPickerView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

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

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


    func pickerView(pickerView: UIPickerView,
                    titleForRow row: Int,
                                forComponent component: Int) -> String? {

        if component == 0 {
            return characters[row]
        } else {
            return weapons[row]
        }

    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int? {
        if component == 0 {
            return characters.count
        } else {
            return weapons.count
        }
    }

}

Replacing deprecated version of the method of protocol UIPickerViewDataSource , if you're using Swift 3 could works for you.

Deprecated Method of Protocol

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

Latest Method of Protocol in Swift 3

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

Note: Same true for other required protocol methods. ie

Deprecated:

func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int

Recent Version:

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int

Because your required delegate method is not correct.

Replace it with this:

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    if component == 0 {
        return characters.count
    } else {
        return weapons.count
    }
}

Your delegate method returns Int? which is not correct.

You have to implement it's function:

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int 
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM