Search code examples
iosswift2uipickerview

UIPickerView default row


If I want to have the default row when the view controller starts as [2] or any other row number, how do I carry that out?

var pickerData = ["2x2","4x4","6x6","8x8","12x12"]    


override func viewDidLoad() {
    super.viewDidLoad()

    totalTilesLabel.text = pickerData[8]

    
    display.text = sentData
    self.picker.delegate = self
    self.picker.dataSource = self

}

This is the UIPicker datasource and delegate.

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return pickerData.count
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return pickerData[row]
}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

}

Solution

  • Set the picker view's selected row to whatever initial row you want in the viewDidLoad method. Here's Swift 3 code. Adjust as needed for Swift 2.

    self.picker.selectRow(8, inComponent: 0, animated: false)