Search code examples
iosswiftuisegmentedcontrol

Crash on switching segment control


I have a tableview with 4 segments on top. At the 1st segment I have loaded 76 rows, at segment 3 I have 4 rows, at 4th segment I have about 25 rows & there's nothing at segment 2. If the rows in each of the segment are not scrolled down and if all of them are at the top(i.e. the first row is visible out of the total number of rows for each segment) then no matter how I switch the tabs, there won't be any crash.

But say for instance if at the 1st segment, I scrolled the rows down and then shifted to the 3rd segment, then there's a crash saying fatal error: Index out of range. Maybe due to mismatch in the number of rows on either tabs. But not sure about the fix. Hope somebody can help...


Solution

  • From this case i came to understand you are using same UITableView for three segments also i came to know your call tableView.reloadData() when you change segment the crash happen because of one segement have more data and other don't have when scroll tableView. tableView's visble index positions not available in other segement's datasource because of that only you get crash and solution for this you need to scroll to the 0th index if count greater than 0 then reload tableView

    when click on other segement before changing value to be populated scroll back to 0th index

     if listArray.count > 0{
          let index = IndexPath(row: 0, section: 0)
          self.tableView.scrollToRow(at: index, at: .bottom, animated: false)
     } 
    

    then change the value for clickedSegement to listArray

    then reload tableview

    self.tableView.reloadData()
    

    Hope this will help you