Search code examples
iosswiftuipickerview

Having trouble with a UIPickerView in iOS


I have an app with a UIPickerView and whenever a certain row of the picker view is selected, a table view below it updates with relevant information. My problem is that whenever the app first opens, the table view is empty even though the first row of the picker view is highlighted/selected by default. I have to scroll down and then back up to the first row in order for it to register as truly selected, and for the table view to update properly.

Is there a way to make it so that the first row automatically gets selected so I don't have to scroll down and back up every time? I know there's a selectRow() function, but that doesn't work. It just does the same thing. In other words, the row "looks" selected, but it's not actually registering that way. Does anyone know if this is just how it is, or is there a way to bypass it?

EDIT: Here's my didSelectRow code for the picker view:

func pickerView(_ pickerView:UIPickerView, didSelectRow row:Int, inComponent component:Int)
{
    let currentState = abbvsList[statePicker.selectedRow(inComponent: 0)]
    parser = XMLParser(contentsOf:(NSURL(string:"http://alerts.weather.gov/cap/\(currentState).php?x=0") as! URL))!
    alerts = []
    exps = []
    sev = []
    summ = []
    eff = []
    urg = []
    cert = []
    link = []
    latList = []
    longList = []
    parser.delegate = self
    parser.parse()
    alertsTable.reloadData()
    if(alerts.isEmpty) {
        alertsTable.isHidden = true
    }
    else {
        alertsTable.isHidden = false
    }
}

Solution

  • An initial method to load data, Try calling it inside viewDidAppear or viewDidLoad.

    //It should be called after the picker view is loaded.
    func loadPickerView(){
        if abbvsList.count > 0 {
            let currentState = abbvsList[0]// get the first element of array
            parser = XMLParser(contentsOf:(NSURL(string:"http://alerts.weather.gov/cap/\(currentState).php?x=0") as! URL))!
            alerts = []
            exps = []
            sev = []
            summ = []
            eff = []
            urg = []
            cert = []
            link = []
            latList = []
            longList = []
            parser.delegate = self
            parser.parse()
            alertsTable.reloadData()
            if(alerts.isEmpty) {
                alertsTable.isHidden = true
            }
            else {
                alertsTable.isHidden = false
            }
        }else{
            //picker view data is empty
        }
    }