我在HomeViewController中实现了UIPickerView。UIPickerView 有 3 个不同的部分,对应 3 个不同的视图控制器。我需要编写什么代码才能从 UIPickerView 中选择一行将我带到相应的 ViewController?
谢谢!
您的 HomeViewController 需要符合 UIPickerViewDelegate
:
class HomeViewController: UIViewController, UIPickerViewDelegate {
然后实现didSelectRow
委托方法UIPickerView
假设你只有一个组件(所以不检查方法中的组件)
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print(row)
if row == 0 {
let vcOne = storyboard?.instantiateViewController(withIdentifier: "firstVC") as! FirstVC
present(vcOne, animated: true, completion: nil)
// first selection, initialize the VC related with it
} else if row == 1 {
let vcTwo = storyboard?.instantiateViewController(withIdentifier: "secondVC") as! SecondVC
present(vcTwo, animated: true, completion: nil)
// second selection, initialize the VC related with it
} else {
// other selections, you get the idea, you can also do switch-case
}
}
在委托方法中,您可以初始化,并根据行推送或呈现不同的视图控制器。