我正在创建我的第一个应用程序,并且希望在UI选择器中选择一个项目时在第二个视图控制器中显示数据。
当单击第一个视图控制器上的搜索栏时,我希望出现一个UI Picker。 UI选择器将显示国家/地区名称。 UI选择器将使用所选国家/地区名称填充搜索栏。当按下一个按钮时,我想对第二个视图控制器执行搜索,然后将其填充有关所选国家/地区的信息。我正在尝试开发我的第一个应用程序,但似乎找不到关于此确切主题的任何教程。选择搜索栏后,如何显示UI选择器?如何根据选定的选择器行将信息传递给第二个视图控制器?
下面是我自己能想到的代码。否则,我很困惑。
import UIKit
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var countryPicker: UIPickerView!
@IBOutlet weak var goButtonPressed: UIButton!
var countryName : [String] = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.countryPicker.delegate = self
self.countryPicker.dataSource = self
countryName = ["Australia", "Bolivia", "Croatia", "Denmark", "Estonia", "France", "Germany", "Hungary"]
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return countryName.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
print (countryName[row])
return countryName[row]
}
}
答案 0 :(得分:0)
这就是我要做的:
首先,在您的第一个View Controller中声明一个变量,并为它分配pickerView的第一个值:
var selectedCountryName: String = countryName[0]
然后,声明以下方法以捕获选择器视图选择并将其分配给先前声明的变量:
// Capture the picker view selection
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent
component: Int) {
selectedCountryName = countryName[row]
}
然后,在第二个视图控制器中,声明相同的selectedCountryName变量:
var selectedCountryName: String = country[0]
最后,在第一个视图控制器的prepareForSegue方法内,将所选国家/地区名称从第一个传递到第二个视图控制器:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! SecondViewController
destinationVC.selectedCountryName = selectedCountryName
}