Mac Catalyst: UITableView focus gets separated from the selection after Programmatically Changing the Selection

After programmatically changing the selection of a UITableview, focus gets separated from the selection if I programmatically select a cell beyond the visible region of the table view. That is to say the focused cell is not the selected cell which any user would consider wrong.

To reproduce

  1. Add a button to select the "Next" row in a table (deselect the previous selected row, then select the next row just below it)
  2. Click the button.
  3. Keep clicking the button to move the table view selection down. Once you select the row outside the visible region of the table view focus cell gets separated from the selection.

I created a bug report on this with a sample project: FB11803433

Trying to scroll the row visible before programmatically changing the selection doesn't always work around the issue. I experimented with -performSelector:withObject:afterDelay: calls and -setNeedsFocusUpdate and -updateFocusIfNeeded calls but it doesn't always seem to work.

Replies

My latest workaround attempt is to override -preferredFocusEnvironments: on UITableView and if the table view has a selected row try to find the cell for it by calling -cellForRowAtIndexPath: and returning it.

Hopefully that'll work.