I have set a picker view like the picture above, as we can see, at the starting point after the view controller appears, the selection will automatically show the first string on the list (London). but I want when the view appears for the first time, it will show string selection of the middle of the list, like the picture below
here is the code I use
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]
}
}
what should I do to achieve that ?
Select the row you want in viewDidLoad
:
override func viewDidLoad() {
super.viewDidLoad()
cityPicker.selectRow(3, inComponent: 0, animated: false)
cityLabel.text = city[cityPicker.selectedRow(inComponent:0)]
}