如何使用 UIPickerView 导航到不同的视图控制器
How can I navigate to a different view controller using UIPickerView
我在我的主页中实现了一个 UIPickerViewViewController。 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
}
}
在委托方法中,您可以根据行初始化、推送或呈现不同的 viewController。
我在我的主页中实现了一个 UIPickerViewViewController。 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
}
}
在委托方法中,您可以根据行初始化、推送或呈现不同的 viewController。