如何将 UIPickerview 选择行重置为默认零行



我有一个应用程序,其UIPickerview有 2 个组件,从 2 个数组中获取数据。当选择组件 3 中的第 1 行时,我已经在第 0 行设置了第二个组件。这很好,但我的问题是当组件 0 中的row发生变化时,我希望将组件 1 重置为第 0 行(作为默认值(。

@IBOutlet weak var myPicker: UIPickerView!
let firstArray = ["a", "b", "c", "d"]
let secondArray = ["A", "B", "C", "D"]
override func viewDidLoad() {
super.viewDidLoad()
myPicker.delegate = self
myPicker.dataSource = self
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch component {
case 0: return firstArray.count
case 1: return secondArray.count
default: break
}
return 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch component {
case 0: return firstArray[row]
case 1: return secondArray[row]
default: break
}
return ""
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if myPicker.selectedRow(inComponent: 0) == 1 {
myPicker.selectRow(3, inComponent: 1, animated: true)
}
}

只需使用else if选择component1中的第一个row,如下所示:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if myPicker.selectedRow(inComponent: 0) == 1 {
myPicker.selectRow(3, inComponent: 1, animated: true)
} else if component == 0 {
myPicker.selectRow(0, inComponent: 1, animated: true)
}
}

最新更新