Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tvOS : Force a button to be focused

I have a UIView with a button on it and need to set the focus on the button when the view is added to the self.view, but I don't know why the button doesn't focus when the view is added!

 - (void)didUpdateFocusInContext:(UIFocusUpdateContext *)context withAnimationCoordinator: (UIFocusAnimationCoordinator *)coordinator {



         if (context.nextFocusedView == backButton) {

             [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:.40 initialSpringVelocity:.60 options:UIViewAnimationOptionAllowUserInteraction animations:^ {

                 context.nextFocusedView.transform = CGAffineTransformMakeScale(1.5, 1.5);
                 context.nextFocusedView.layer.shadowOffset = CGSizeMake(0, 10);
                 context.nextFocusedView.layer.shadowOpacity = 1;
                 context.nextFocusedView.layer.shadowRadius = 15;
                 context.nextFocusedView.layer.shadowColor = [UIColor redColor].CGColor;
                 context.nextFocusedView.layer.shadowOpacity = 1;

             } completion:nil];


         }

}

I also tried other properties :

- (void)openView {

        [backButton preferredFocusedView];
        [backButton canBecomeFocused];
        [backButton setNeedsFocusUpdate];

       [self.view addSubView:customView];
}

- (UIView *)preferredFocusedView {

       return [backButton preferredFocusedView];   
}

but none of these worked!

like image 413
iOS.Lover Avatar asked Nov 27 '15 13:11

iOS.Lover


2 Answers

Let's assume you have a UIViewController with a property backButton (a UIButton). This button has been setup properly and is inside the visible bounds of the ViewController's view. It should also have an action defined for the event UIControlEventPrimaryActionTriggered.

If you want the button to be focused when the UIViewController's view is shown, return that button for preferredFocusedView:

- (UIView *)preferredFocusedView {
   return self.backButton;
}

But if you want it to be focused at a different time in the view lifecycle or user flow, you'd use a different method.

For example, if you want a button to become focused at an arbitrary time: Make sure the button will be returned via the preferredFocusedView, then call setNeedsFocusUpdate on the focus context (in a simple case, the view controller).

like image 70
Jess Bowers Avatar answered Nov 13 '22 14:11

Jess Bowers


This should work.

- (UIView *)preferredFocusedView {

       return backButton;   
}

Instead of returning [backButton preferredFocusedView], simply return backButton.

like image 41
Gene De Lisa Avatar answered Nov 13 '22 14:11

Gene De Lisa