简体   繁体   中英

uipickerview selecting default row

I am using a uipickerview to choose songs from. The problem is when I press play without interacting with the picker view (ie trying to play the first song that is already selected/loaded by the picker view.) I get an error:

fatal error: unexpectedly found nil while unwrapping an Optional value

I have the code below set for didSelectRow:

     func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

            musicChoice = songs[row]
    }

And as I understand, this only initiates once the user scrolls/ interacts with the picker view - so I am trying to use selectedRow somehow but am messing up, any ideas?

Updated pickerview code below:

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]

}

The did select row method is self explanatory it says didSelectRow so you are right without interacting with the rows it doesn't initialise any thing.

Instead of selected row you can always initialise the first songs value to be played. ie

musicChoice = songs[0]

while you declare the musicChoice variable. That would solve the purpose.

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