如何在 tvOS (AppleTV) 上的 UICollectionView 运行 的单元格中获取按钮以获取焦点?

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

这是我最基本的代码。它在 UICollectionView 中显示了五个单元格(每个单元格中都有一个简单的按钮)。所有按钮都指向单个 IBAction 方法。这是 Main.storyboard.

中的所有设置

虽然我无法让 tvOS 聚焦按钮。知道为什么吗?

#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

默认情况下,UICollectionViewCell 是可聚焦的,这意味着它将获得焦点而不是它的子视图,但是您可以通过覆盖 preferredFocusedView 和 return 来覆盖此功能。您希望获得焦点的视图。

- (UIView *)preferredFocusedView
{
    return _button;
}

阅读更多关于 Initial Focus and the Preferred Focus Chain

或者你可以

- (BOOL)collectionView:(UICollectionView *)collectionView canFocusItemAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}