PickerView只显示'?'

时间:2017-05-18 15:07:35

标签: ios swift uipickerview

这是我的源代码,我所做的是在storyBoard上制作选择器视图。通过contorl + drag在此控制器中创建IBOutlet。

但它可以编译,只有'?'出现在选择器视图中。

问题出在哪里?

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 个答案:

答案 0 :(得分:2)

您错过了dataSource方法中的forComponent参数。将其添加到titleForRow函数中,如下所示:

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

这可以解决您遇到的问题。