How can I keep the first row of a UITableView focused during a data update?

932 views Asked by At

I have a UITableView that presents a timeline of data on tvOS. It is dynamically updated via an NSFetchedResultsController.

When the table is updated, new cells are added at the top. However: the previously selected cell remains focused, but the behaviour I need is for the focus to shift to the 'newest' (i.e. topmost) cell after the data update.

How can I achieve this?

1

There are 1 answers

0
beyowulf On

Not sure what your code looks like, but you can create a property to keep track of whether the table is actively updating.

var tableViewIsUpdating = false

You can use this to determine if you want the normal focus before or to return the first row of your table view:

override var preferredFocusedView: UIView?{
    get {
        if updating {
            return self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))
        }
        return super.preferredFocusedView
    }
}

Then in your NSFetchedResultsControllerDelegate set if it's updating or not:

func controllerWillChangeContent(controller: NSFetchedResultsController){
    self.tableViewIsUpdating = true
}

func controllerDidChangeContent(controller: NSFetchedResultsController) {
    self.setNeedsFocusUpdate()
    self.updateFocusIfNeeded()
    self.updating = false
}

You can find more information here on how to update focus programmatically.