PickerView shows only '?'

2019-09-16 18:20发布

This is my source code and what I have done is make picker view on storyBoard. Make IBOutlet in this controller by contorl+drag.

It can be compiled however, only '?' appears in the picker view.

Where is the problem?

import UIKit

class SelectViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate{
    var songNames = ["test1","test2","test3"]

    @IBOutlet weak var songPicker: UIPickerView!

    override func viewDidLoad(){ 
        songPicker.delegate = self
        songPicker.dataSource = self

    }

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

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

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int) -> String? {
        return songNames[row]
    }
}

1条回答
虎瘦雄心在
2楼-- · 2019-09-16 18:49

You have missed the forComponent parameter from the dataSource method. Add it in your titleForRow function like this:

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return songNames[row]
}

This should fix the problem you are having.

查看更多
登录 后发表回答