在Xcode Swift中使用PickerView在此代码中出现错误:
func pickerView(pikcerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return pickerDate [row] // Cannot convert return expression of type '[String]' to return type 'String?'
}
PickerView的完整代码:
@IBOutlet weak var inputpickerdate: UIPickerView!
// var pickerList = ["test","test2","test3"]
var pickerDate: [[String]] = [[String]] ()
//[pickerModel] ()
var selected: String?
override func viewDidLoad() {
super.viewDidLoad()
self.inputpickerdate.delegate = self
self.inputpickerdate.dataSource = self
pickerDate = [["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"], ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"]]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerDate.count
}
func pickerView(pikcerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return pickerDate [row]
}
我正在尝试创建一个带有星期几,日期和月份的PickerView,例如3月2日星期一
但是,我已经这样做并获得了
错误:无法将类型为[[String]'的返回表达式转换为返回值 输入“字符串?”
在我的func titleForRow
中,不确定我为什么得到这个。
答案 0 :(得分:0)
您有一个列表列表。
[]
->列表。
[[]]
->列表列表。
您将返回列表[]
而不是String?
。
在您的情况下,您必须使用类似以下的内容:
func pickerView(pikcerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerDate[component][row] // if component starts with 0.
}
当然,您必须做出逻辑以获取正确的字段。
答案 1 :(得分:0)
首先,您使用了错误的titleForRow
委托方法。应该是:
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
接下来,您需要替换
return pickerDate [row]
与
return pickerDate[component][row]
您的方法将是:
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerDate[component][row]
}
您的选择器将如下所示:
答案 2 :(得分:0)
您将返回Array = return pickerDate [row]
的字符串,该字符串应为单个字符串。