How does restoresFocusAfterTransition work?

As covered in one of the tvOS videos from WWDC 2016, UIViewController has a property called restoresFocusAfterTransition, which is supposed to re-focus whatever view was focused when that controller is transitioned back to.


I'm running into some issues with presenting a modal view controller, and the focus engine putting focus on a different item when the modal is dismissed. Can anyone (from Apple, maybe?) provide any insight into the mechanism that's used for this property? How does this interact with the other parts of the focus engine, such as preferredFocusEnvironments?

Replies

After several hours, I believe I've found that my problem was disrelated to restoresFocusAfterTransition.


1. ViewController1 has a UIImageView with an assigned UIImage, "cat.jpg". Responding to a button press, ViewController1 creates ViewController2 and presents it modally, passing ViewController2 a reference to the cat UIImage.

2. On ViewController2's viewDidLoad(), it assigns the cat UIImage to its own UIImageView.

3. When hitting Menu, ViewController2 dismisses as expected, but when ViewController1 returns to the foreground, focus has transferred to the top-left-most focusable element in its view hierarchy. The expected behavior would be for the original button (that was focused before the presentation) to have regained focus.


The problem was solved in #2, by using DispatchQueue.main.async() to assign the cat image to the UIImageView on the main thread. I'm not sure why this was necessary, but as soon as I did it, focus restored properly to the button upon VC2's dismissal.


I remember the datum that UIKit doesn't play well with background threads, and in the past I've seen violation of this cause my app to crash, so I believe it. But I was assigning the image in a viewDidLoad() method, so...I'm not sure what the deal is.


Regardless, my question about restoresFocusAfterTransition stands. Also, if anyone can explain the above phenomena, that would be awesome.