Using .prefersDefaultFocus and .focusScope

Daily Coding Tip 050

Note that due to a scheduling error, Daily Coding Tip 049 was sent out a day early, so this will be the last Daily Coding Tip for free subscribers.

On tvOS 14 and watchOS 7, we now have the ability to declare what user interface element we want to be focused by default. On tvOS, this matters because pressing the Touch surface of the Siri remote performs the action of the Button with focus. On watchOS, the focused element is controlled by moving the Digital Crown.

In a VStack, the top View will always gain focus by default, unless we take steps to prevent this behaviour.

To do this, we need to define the scope in which the focus system can be overridden. Declaring a focus scope requires a @Namespace, a subject on which there’s more detail in the .matchedGeometryEffect section above. The important thing is that I gave a Namespace.ID with my property, which I also called namespace. I passed this to the .focusScope modifier on the VStack, and now we have our scope.

Get more Daily Coding Tips in your inbox!