Member-only story
PreferredFocusEnvironments, setNeedsFocusUpdate, updateFocusIfNeeded, becomeFocused, FocusGuide
Focus shows which item is currently selected and ready for action.
Any items on your screen that the user can interact with, like buttons, text fields, or images. On Apple TV, these are the elements that can be highlighted when navigating with the remote.
1. PreferredFocusEnvironments
(Controlling Focus in Nested Views)
In tvOS apps, the system automatically decides which view gets focus, but you can guide the system using PreferredFocusEnvironments
. This is useful when you have nested views and want to specify which view should get focus when the user navigates to that screen.
Example:
Imagine a screen with two sections: a menu on the left and content on the right. When the screen appears, you want the focus to start on a specific button in the content section, rather than the menu.
class CustomViewController: UIViewController {
// Suppose you have two buttons
let menuButton = UIButton()
let contentButton = UIButton()
override var preferredFocusEnvironments: [UIFocusEnvironment] {
// Returning the contentButton to set it as the preferred focus
return [contentButton]
}
override func viewDidLoad() {
super.viewDidLoad()
// Add the buttons to your view hierarchy
view.addSubview(menuButton)…