简体   繁体   中英

how to set picker view to be in the middle of selection list?

在此处输入图片说明

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)]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM