I'm using Xcode Version 13.1
I use UIPickerView, but when I choose value its jump to another one, I have 10 items [item 0 ... item 9]
when I choose item 1 the value jumps to 6, how can I solve it?
Here I'm choosing "Item 1" but Xcode choose and print 6 instead of 1
my code:
import UIKit
class LengthViewController: UIViewController {
@IBOutlet weak var pickerView: UIPickerView!
let pickerData = ["Item 0","Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8","Item 9"]
override func viewDidLoad() {
super.viewDidLoad()
pickerView.delegate = self
pickerView.dataSource = self
}
}
extension LengthViewController: UIPickerViewDelegate{
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
print(row)
return pickerData[row]
}
}
extension LengthViewController: UIPickerViewDataSource{
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
}
}
CodePudding user response:
The problem is that you're printing at a bad moment. You printing in pickerView(_:titleForRow:forComponent)
. This is like looking to see how the sausage is made. You are assuming that just because you choose a certain row, that is also the row that the picker view wants the title for. But there is actually no connection between those two things. The row that needs its title is not the row you chose.
Instead, implement pickerView(_:didSelectRow:inComponent:)
and put your print
call there. You will see that when you choose a row, that is indeed the row that the picker view thinks you chose.