Search code examples
iosswifttvosuifocusguide

TV OS UIFocusEnvironment Not focusing Button


Hi all I am a beginner in TV OS App development.

As mentioned below image, I could move the buttons,

Button1 -> Right Arrow -> focusing Button 2

I have noticed that, When moving down next (From Button2 to Button4) focusing item frame should be with in the boundary of the Button2 and Button6.

I want to move Button1 to Button 3 when down pressed. (Button3 is not in the boundary between Button1 and Button5)

How do I fix this?

Any help will highly appreciated. Thanks in Advance. enter image description here


Solution

  • For this you can place a UIFocusGuide to the left of button 3. (https://developer.apple.com/documentation/uikit/uifocusguide)

    The focus guide is a invisible layout guide element that will "catch" focus and redirect it to whatever view you specify.

    Edit: Full documentation with Sample

    Example:

    let focusGuide = UIFocusGuide()
    view.addLayoutGuide(focusGuide)
    focusGuide.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    focusGuide.rightAnchor.constraint(equalTo: button3.rightAnchor).isActive = true
    focusGuide.topAnchor.constraint(equalTo: button3.topAnchor).isActive = true
    focusGuide.bottomAnchor.constraint(equalTo: button3.bottomAnchor).isActive = true
    focusGuide.preferredFocusEnvironments = [button3]