当 UIImageView 聚焦在 UICollectionViewCell 中时,如何更改它的默认动画行为?

How can I change the default animation behavior of a UIImageView when it is focused inside a UICollectionViewCell?

我在每个单元格中有一个 UICollectionViewController 和一个 UIImageView 作为 IBOutlet。我为图像视图设置了 imageView.adjustsImageWhenAncestorFocused = true,当相关单元格聚焦时,图像视图变得太大。只是想知道是否有任何方法可以控制图像视图的动画行为。我知道我可以覆盖 didUpdateFocusInContext(_:withAnimationCoordinator:),但无法找到如何处理 hover 事件。
任何帮助,将不胜感激。

因此,当焦点位于当前选定的单元格时,请使用 didUpdateFocusInContext 函数来更新您的单元格。

首先禁用图像视图 adjustsImageWhenAncestorFocused 属性 然后根据您的意愿更改图像视图的大小。

定义两种不同的尺寸并将其用于聚焦单元格和其余单元格。

CGSize originalCellSize = CGSizeMake(225, 354);
CGSize focusCellSize = CGSizeMake(240, 380);

- (void)didUpdateFocusInContext:(UIFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator
{
    [coordinator addCoordinatedAnimations:^{
        if (self.focused) {
            self.imageView.frame.size = focusCellSize;
        } else {
            self.imageView.frame.size = originalCellSize;
        }
    } completion:nil];
}

使用 animatewithDuration: 在更改单元格大小时提供更好的动画样式,或者为 imageview 使用 alpha 或阴影效果以获得更完美的外观。

也许更好的解决方案是在单元格(或单元格的 contentView)上使用 CGAffineTransform 来处理这个问题。这样您就不需要更改视图框架(您也可以在 self.imageView.transform 上进行变换,如果这更适合您的话)。

#pragma mark - UIFocusEnvironment

- (void)didUpdateFocusInContext:(UIFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator {
    if (self.focused) {
        [coordinator addCoordinatedAnimations:^{
            self.transform = CGAffineTransformMakeScale(1.1f, 1.1f);
        } completion:nil];
    } else {
        [coordinator addCoordinatedAnimations:^ {
            self.transform = CGAffineTransformMakeScale(1.f, 1.f);
        } completion:nil];
    }
}