How do I get buttons in a cell on a UICollectionView running on tvOS (AppleTV) to take focus?
Asked Answered
I

2

5

Here is my very basic code. It shows five cells in a UICollectionView (each cell with a simple button in it). All buttons point to the single IBAction method. This is all setup within the Main.storyboard.

I can't get tvOS to take focus of the buttons though. Any idea why?

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 5;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
    return cell;
}

- (IBAction)buttonAction
{
    // do stuff
}

@end

enter image description here

Incivility answered 14/9, 2015 at 2:4 Comment(0)
L
12

By default UICollectionViewCell is a focusable means it will get focus instead of its subview, but you can override this functionality by overriding preferredFocusedView and return which ever view you want to get focus.

- (UIView *)preferredFocusedView
{
    return _button;
}

read more about Initial Focus and the Preferred Focus Chain

Longobard answered 14/9, 2015 at 7:11 Comment(1)
For any customization for UICollectionviewCell you can just override : override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator)Automata
B
4

or you can just

- (BOOL)collectionView:(UICollectionView *)collectionView canFocusItemAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}
Baseman answered 1/3, 2016 at 9:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.