Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload tableView section without reloading header section - Swift

I'm trying to reload tableView section instead of reloading the whole tableview because I have a textfield in the header section and when I call self.tableView.reloadData() my keyboard get closed.

I've tried the code below but I get this error Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete row 5 from section 2 which only contains 4 rows before the update' So please where would be my issue?

    let newCount = self.placeArray.count

    var newIndexPaths = NSMutableArray(capacity: newCount)

    for var i = 0 ; i < newCount ; i++ {
    var indexPath = NSIndexPath(forRow: i, inSection: 2)
        newIndexPaths.addObject(indexPath)
    }

    self.tableView.beginUpdates()
    self.tableView.reloadRowsAtIndexPaths(newIndexPaths as [AnyObject], withRowAnimation: UITableViewRowAnimation.None)
    self.tableView.endUpdates()
like image 825
CAN Avatar asked Sep 07 '15 14:09

CAN


3 Answers

You could use UITableView's reloadSections method instead.

tableView.reloadSections(IndexSet(integer: 2), with: .none)
like image 105
hennes Avatar answered Oct 21 '22 03:10

hennes


Swift 3.0.1:

let sectionIndex = IndexSet(integer: 0)

tableView.reloadSections(sectionIndex, with: .none) // or fade, right, left, top, bottom, none, middle, automatic
like image 21
Danut Pralea Avatar answered Oct 21 '22 03:10

Danut Pralea


Swift 3.1 Xcode 8.3.3 Answer :)

The problem is - each section includes header of course, so section is:

section = header + footer + rows

The answer is - reload rows directly by IndexPath. Example:

  1. Let's say you've got 1 section in your table and 'array' of something you use as datasource for table:

    let indexes = (0..<array.count).map { IndexPath(row: $0, section: 0) }

  2. Now we've got array of indexes of cell we want to reload, so:

    tableView.reloadRows(at: indexes, with: .fade)

like image 14
Gennadii Tsypenko Avatar answered Oct 21 '22 04:10

Gennadii Tsypenko