Moloixo Moloixo - 2 months ago 8
Objective-C Question

How can I get a specific button running on tvOS (AppleTV) to take focus? (Objective C)

The project have some views with different buttons. When I hide a view and show the other view, I can't get the focus on my button.

I think is related to

setNeedsFocusUpdate
. I have read the Apple doc. There is not any example.

Does anyone know how to do it and put an example (Objective C)?

Answer

You need to override preferredFocusedView, and when you are hiding one view and showing there call this method setNeedsFocusUpdate, your preferredFocusedView implementation should be something like this

- (UIView *)preferredFocusedView
{
    // Add your logic here, it could be more complicated then what is below
    if (view1.hidden)
    {
        return _button;
    }
    else 
    {
        return _button2
    }
}

And if you want to make custom view get focus, override canBecomeFocused method and return true

Edit

You can use add a breakpoint and execute this command po [buttonYouWantToFocus _whyIsThisViewNotFocusable] it will tell you why its not focusable.