1. 首先,您需要创建一个dataSource,您可以在UIPickerView 中使用它。对于要在UIPickerView 中显示的所有rows,它必须包含title 和link,即
let data = [
[
"title": "Kansas",
"link": "https://www.dmv.org/ks-kansas/"
],
[
"title": "Title-1",
"link": "Link-1"
],
[
"title": "Title-2",
"link": "Link-2"
],
[
"title": "Title-3",
"link": "Link-3"
]
]
2.接下来,您需要在您的UIViewController 中实现UIPickerViewDataSource 和UIPickerViewDelegate 方法,即
func numberOfComponents(in pickerView: UIPickerView) -> Int
{
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
return data.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
return data[row]["title"]
}
不要忘记在viewDidLoad() 中设置UIPickerView 的delegate 和dataSource。
@IBOutlet weak var pickerView: UIPickerView!
override func viewDidLoad()
{
super.viewDidLoad()
}
3. 现在,按下UIButton,您需要在UIPickerView 中获取selected row's link 并将其发送到包含UIWebView 的AnotherViewController,即
@IBAction func onTapDoneButton(_ sender: UIButton)
{
let anotherController = self.storyboard?.instantiateViewController(withIdentifier: "AnotherViewController") as! AnotherViewController
anotherController.urlString = self.data[self.pickerView.selectedRow(inComponent: 0)]["link"]
self.present(anotherController, animated: true, completion: nil)
}
4.这是AnotherViewController 的代码,其中包含UIWebView。
class AnotherViewController: UIViewController
{
var urlString: String?
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad()
{
super.viewDidLoad()
if let urlString = self.urlString, let url = URL(string: urlString)
{
self.webView.loadRequest(URLRequest(url: url))
}
}
}
如果您仍然遇到任何问题,请告诉我。