Moloixo
Moloixo

Reputation: 23

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)?

Upvotes: 2

Views: 2915

Answers (4)

Andra Todorescu
Andra Todorescu

Reputation: 628

Another option (if you don't want to use preferredFocusedView) is, instead of setting your view to be hidden, simply remove it from it's superview, like so:

myView.removeFromSuperview()

This automatically takes the focus away from the button that is removed and gives it to another one that is still on screen.

Upvotes: 0

Thomas Jeans
Thomas Jeans

Reputation: 398

I realize your question is specific to Objective-C but here is a way to solve for this in Swift. You need to override the preferredFocusedView property.

override var preferredFocusedView: UIView? {
    guard primaryView.hidden == false else {
        return secondaryView
    }
    return primaryView
}

Then just call setNeedsFocusUpdate() whenever an event happens that causes your views to be hidden. Hope this helps...

Upvotes: 0

Adnan Aftab
Adnan Aftab

Reputation: 14487

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.

Upvotes: 3

Per Ekstig
Per Ekstig

Reputation: 41

If you are adding a sub view programmatically, maybe this is what you want:

- (UIView *)preferredFocusedView {
    return [view1 preferredFocusedView];
}

Upvotes: 0

Related Questions