我有一个UIPickerView,其中一些行每个都有标题。我要的是单击标题时,链接到该标题的新视图控制器,就像单击按钮将我带到新VC一样。如何在选择器视图中使用行标题来做到这一点?
我试图将特定的一行拖到视图控制器中,但是整个选择器都被选中了。
答案 0 :(得分:1)
您可以设置pickerView委托,然后按入viewController
示例代码:
class ViewController: UIViewController {
@IBOutlet private weak var pickerView: UIPickerView!
struct PickerData {
let viewControllerId: String
let storyboardId: String
let title: String
}
private var pickersData: [PickerData] = []
override func viewDidLoad() {
super.viewDidLoad()
loadData()
pickerView.delegate = self
pickerView.dataSource = self
}
private func loadData() {
pickersData.append(
ViewController.PickerData(viewControllerId: "ViewController1", storyboardId: "Main", title: "Foo")
)
pickersData.append(
ViewController.PickerData(viewControllerId: "ViewController1", storyboardId: "Main", title: "Bar")
)
}
private func createViewController(from index: Int) -> UIViewController {
let model = pickersData[index]
let viewController = UIStoryboard(name: model.storyboardId, bundle: nil).instantiateViewController(withIdentifier: model.viewControllerId)
return viewController
}
private func pushViewController(viewController: UIViewController) {
// If Navigation
navigationController?.pushViewController(viewController, animated: true)
// If present
//present(viewController, animated: true, completion: nil)
}
}
extension ViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickersData.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickersData[row].title
}
}
extension ViewController: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
pushViewController(viewController: createViewController(from: row))
}
}
答案 1 :(得分:0)
@IBOutlet weak var myPickerView: UIPickerView!
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
performSegue(withIdentifier: "segue\(row)", sender: nil)
}
从您的视图而不是pickerView中拖拽segues