Search code examples
stringglobal-variablesswift2uipickerviewxcode7

UIPickerView start with selected row in middle


When the user selects a state from a UIPickerView, it takes them to a different viewController with data for the selected state. When they hit the 'back' button and go to the viewController for the pickerView it always starts at the top with the first state, in this case Arizona. How can I make it already scrolled to the middle and have Tennessee selected for example, if that was the state they originally selected? I'm using Xcode 7 and Swift 2, Thank you!

I have a UIPickerView that gets it data from:

let pickerData = ["Arizona", "Arkansas", "California","Tennessee", "Texas", "Utah", "Virginia"]

When the user selects a state in the pickerView it takes that value and adds it to a variable:

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    //Takes the selected state and adds it to the variable 'currentState'
    currentState = pickerData[row]
    savedStateGV = currentState
}

'savedStateGV' is a Global variable and 'currentState' is a local variable. Both are String types.

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

Solution

  • you could define an attribute middleOfPicker (an Integer) in your viewcontroller and you could set this attribute in the routine "viewDidLoad" (yourpicker is the IBOutlet-name you gave your picker) using the code sequence:

    middleOfPicker = pickerData.count / 2
    yourpicker.selectRow = middleOfPicker
    

    Finally, the action routine of your "back button" then should include the statement:

    yourpicker.selectRow = middleOfPicker