Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIPickerView is Selecting the Wrong Row-Swift

So I have UIPickerView that isn't working the way I want it to. It works correctly about 3/4 of the time, but the other 1/4 it doesn't.

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

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

}

func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView
{
    activeQuizPlace = row
    var pickerLabel = UILabel()
    pickerLabel.textColor = UIColor.whiteColor()
    pickerLabel.text = listsArray[row]
    pickerLabel.font = UIFont(name: "Georgia", size: 22)
    pickerLabel.textAlignment = NSTextAlignment.Center
    return pickerLabel
}

The listsArray contains 5 items(which are strings). Rows 0-2 work correctly 100% of the time. However when row 3 is selected it occasionally says that row 1 was, and when row 4 is selected it sometimes says that row 2 was. I think the problem has something to do with the last function I have that controls the UIPickerView. I just copied that code from this website as a way to change the color and font of the text. Before I was using this function I never had a problem with it, or at least never noticed one. Side note: I am using Xcode 6.3.2

I need a way for the picker view to work correctly, as well as to be able to change its font and color. I would love help with this I've been looking for answers online for 2 hours and can't figure out what I'm doing wrong, thanks in advance!

like image 587
Jaxon Avatar asked Sep 15 '25 14:09

Jaxon


1 Answers

I think you need to remove the line activeQuizPlace = row from the code you have shown and then add this function below.

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    activeQuizPlace = row
}

The function you were using is not called with the index that the user selects, it is called with the index that the system needs for drawing the views.

The suggested function should be the one you are after (hopefully).

like image 189
Mellson Avatar answered Sep 17 '25 04:09

Mellson