我正在使用uipickerview来选择歌曲。问题是当我按下播放而不与选择器视图交互时(即尝试播放已经由选择器视图选择/加载的第一首歌曲。)我收到错误:
致命错误:在解包可选值时意外发现nil
我为didSelectRow设置了以下代码:
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
musicChoice = songs[row]
}
据我了解,这只会在用户滚动/与选择器视图交互时启动 - 所以我试图以某种方式使用selectedRow但是搞乱,任何想法?
更新了下面的选择器视图代码:
var songs:[String] = []
var musicChoice = "Something"
let foods = ["Apples", "Bananas", "Corn", "Beans", "Tomatoes"]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return songs[row]
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return songs.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
musicChoice = songs[row]
}
答案 0 :(得分:1)
did select行方法是自我解释的,它说if (t1.timeClosed.d.year < t2.timeClosed.d.year)
return true;
if (t1.timeClosed.d.year > t2.timeClosed.d.year)
return false;
if (t1.timeClosed.d.month < t2.timeClosed.d.month)
return true;
if (t1.timeClosed.d.month > t2.timeClosed.d.month)
return false;
所以你是正确的,没有与它没有初始化任何东西的行交互。
您可以随时初始化要播放的第一首歌曲,而不是选定的行。即
didSelectRow
当您声明musicChoice = songs[0]
变量时。这样可以解决目的。