如何将选择器视图设置在选择列表的中间?

时间:2018-02-12 02:47:57

标签: ios swift uipickerview

enter image description here

我已经设置了如上图所示的选择器视图,我们可以看到,在视图控制器出现后的起始点,选择将自动显示列表中的第一个字符串(伦敦)。但我希望当视图第一次出现时,它会显示列表中间的字符串选择,如下图所示

enter image description here

这是我使用的代码

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

我该怎么做才能实现这一目标?

1 个答案:

答案 0 :(得分:5)

viewDidLoad中选择您想要的行:

override func viewDidLoad() {
    super.viewDidLoad()
    cityPicker.selectRow(3, inComponent: 0, animated: false)
    cityLabel.text = city[cityPicker.selectedRow(inComponent:0)]
}