Xcode 选择器视图跳转到另一个值而不是所选值
Xcode Picker View is jumping to another value instead of the selected one
我正在使用 Xcode 版本 13.1
我使用 UIPickerView,但是当我选择值时它会跳转到另一个,我有 10 个项目 [item 0 ... item 9]
当我选择item 1时,值跳到6,如何解决?
Here I'm choosing "Item 1" but Xcode choose and print 6 instead of 1
gif
我的代码:
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
}
}
问题是您打印的时机不对。您在 pickerView(_:titleForRow:forComponent)
中打印。这就像看看香肠是如何制作的。您假设仅仅因为您 选择 某一行,该行也是选择器视图想要 title 的行。但实际上这两件事之间没有任何联系。需要标题的行不是您选择的行。
相反,实施 pickerView(_:didSelectRow:inComponent:)
并将您的 print
调用放在那里。您会看到,当您选择一行时,该行确实是选择器视图认为您选择的行。
我正在使用 Xcode 版本 13.1
我使用 UIPickerView,但是当我选择值时它会跳转到另一个,我有 10 个项目 [item 0 ... item 9]
当我选择item 1时,值跳到6,如何解决?
Here I'm choosing "Item 1" but Xcode choose and print 6 instead of 1
gif
我的代码:
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
}
}
问题是您打印的时机不对。您在 pickerView(_:titleForRow:forComponent)
中打印。这就像看看香肠是如何制作的。您假设仅仅因为您 选择 某一行,该行也是选择器视图想要 title 的行。但实际上这两件事之间没有任何联系。需要标题的行不是您选择的行。
相反,实施 pickerView(_:didSelectRow:inComponent:)
并将您的 print
调用放在那里。您会看到,当您选择一行时,该行确实是选择器视图认为您选择的行。