gpt4 book ai didi

ios - 将 UIPickerView 行标题链接到新的 View Controller

转载 作者:行者123 更新时间:2023-11-29 05:37:54 26 4
gpt4 key购买 nike

我有一个 UIPickerView,其中一些行每行都有一个标题。我想要的是,当单击一个标题时,会链接到一个特定于该标题的新 View Controller ,就像单击按钮将我带到一个新的 VC 一样。如何在选择器 View 中使用行标题来做到这一点?

我试图将特定行拖到 View Controller 中,但整个选择器被选中。

最佳答案

您可以设置pickerView委托(delegate),然后可以推送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))
}
}

关于ios - 将 UIPickerView 行标题链接到新的 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56857156/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com