在tvOS上,如何聚焦于UICollectionViewCells?

8

我刚接触tvOS。我使用Objective-C创建了一个使用XIB文件的UICollectionView。如何让UICollectionViewCell获取焦点?

我在单元格中有一个标签和一个图像视图,我想要让标签和图像视图都获得焦点。


请提供更多关于您所做的事情以及遇到问题的详细信息,不要要求教程或解释。 - Prafulla Kumar Sahu
3个回答

17

UICollectionViewCell 默认情况下没有焦点外观,但是您可以自己添加一个来实现。

- (void)didUpdateFocusInContext:(UIFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator
{
    if (self.focused)
    {
        // Apply focused appearence,
        // e.g scale both of them using transform or apply background color 
    }
    else
    {
       // Apply normal appearance
    }
}

或者

如果你只想关注像缩放集合视图单元格时放大ImageView,你可以在awakeFromNib方法中这样做

self.imageView.adjustsImageWhenAncestorFocused = YES;
self.clipsToBounds = NO;

应该是'clipsToBounds'(缺少's')。 - Idan Moshe
@IdanMoshe 很好地发现了。像这样非常微小的错别字通常可以直接进行编辑,没有问题。 - Fattie

4

将以下内容添加到collectionview的自定义类中:

override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) { 
 if (self.focused) {
   collectionView.image.adjustsImageWhenAncestorFocused = true
 } else {
   collectionView.image.adjustsImageWhenAncestorFocused = false
 } 
} 

3
将以下方法添加到您的collectionview单元格中。它将仅显示焦点单元格的标题,从而完全展现焦点的外观和感觉。
override func awakeFromNib() {
        super.awakeFromNib()

        // These properties are also exposed in Interface Builder.
        imageView.adjustsImageWhenAncestorFocused = true
        imageView.clipsToBounds = false

        title.alpha = 0.0
    }

    // MARK: UICollectionReusableView

    override func prepareForReuse() {
        super.prepareForReuse()

        // Reset the label's alpha value so it's initially hidden.
        title.alpha = 0.0
    }

    // MARK: UIFocusEnvironment

    override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
        /*
         Update the label's alpha value using the `UIFocusAnimationCoordinator`.
         This will ensure all animations run alongside each other when the focus
         changes.
         */
        coordinator.addCoordinatedAnimations({
            if self.focused {
                self.title.alpha = 1.0
            }
            else {
                self.title.alpha = 0.0
            }
            }, completion: nil)
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接