我已经设置了如上图所示的选择器视图,我们可以看到,在视图控制器出现后的起始点,选择将自动显示列表中的第一个字符串(伦敦)。但我希望当视图第一次出现时,它会显示列表中间的字符串选择,如下图所示
这是我使用的代码
class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource {
@IBOutlet weak var cityLabel: UILabel!
@IBOutlet weak var cityPicker: UIPickerView!
let city = ["London","New York","Tokyo","Kuala Lumpur","Bali","Manchester","Madrid"]
override func viewDidLoad() {
super.viewDidLoad()
// UIPickerView Delegate dan Datasource sebagai self sudah dilakukan melalui interface builder dengan mendrag ke tombol lingkaran kuning dari pickerview nya
cityLabel.text = city[6]
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return city.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return city[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
cityLabel.text = city[row]
}
}
我该怎么做才能实现这一目标?
答案 0 :(得分:5)
在viewDidLoad
中选择您想要的行:
override func viewDidLoad() {
super.viewDidLoad()
cityPicker.selectRow(3, inComponent: 0, animated: false)
cityLabel.text = city[cityPicker.selectedRow(inComponent:0)]
}