TVOS 调整ImageWhenAncestorFocused Size

TVOS adjustsImageWhenAncestorFocused Size

使用 imgView.adjustsImageWhenAncestorFocused = true 聚焦时是否可以调整 ImageView 的 size/frame?

一直在网上搜索,但找不到任何可以设置效果缩放大小的东西,似乎只是一些默认值。

看来你做不到。而且我认为 Apple 不允许这样做是有原因的。

非常detailed human interface guidelines for tvOS。他们建议具有不同列数的网格布局的间距和项目大小,以便观看体验最佳:

The following grid layouts provide an optimal viewing experience. Be sure to use appropriate spacing between unfocused rows and columns to prevent overlap when an item is brought into focus.

我想重点 UIImageView 的 "default" 框架考虑了这些推荐的项目尺寸。而且 Apple 不允许更改它,因为它可能会导致问题,比如其他网格项目被重叠。

因此您不能修改焦点 UIImageView 的框架,但您可以 间接访问 它 - 通过使用 focusedFrameGuide property .

您可以通过 imgView.transform 调整大小。如果您的 imgView 在另一个视图内(例如在 UICollectionViewCell 内),您可以使用下面的代码在接收焦点时将图像缩小 10%

override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
    super.didUpdateFocus(in: context, with: coordinator)
    if context.nextFocusedView === self {
        coordinator.addCoordinatedAnimations({
            self.imgView.transform = self.transform.scaledBy(x: 0.9, y: 0.9)
        }, completion: nil)
    }
    if context.previouslyFocusedView === self {
        coordinator.addCoordinatedAnimations({
            self.imgView.transform = .identity
        }, completion: nil)
    }
}

您还可以使用 adjustsImageWhenAncestorFocused = true 和下一个代码计算 UIImageView 的系统焦点比例:

let xScale = imgView.focusedFrameGuide.layoutFrame.size.width / imgView.frame.size.width 
let yScale = imgView.focusedFrameGuide.layoutFrame.size.height / imgView.frame.size.height 

如果你想在关注 UIImageViewadjustsImageWhenAncestorFocused = true 时删除比例,请使用:

override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
    super.didUpdateFocus(in: context, with: coordinator)
    let xScale = imgView.focusedFrameGuide.layoutFrame.size.width / imgView.frame.size.width 
    let yScale = imgView.focusedFrameGuide.layoutFrame.size.height / imgView.frame.size.height 
    if context.nextFocusedView === self {
        coordinator.addCoordinatedAnimations({
            self.imgView.transform = self.transform.scaledBy(x: 1 / xScale, y: 1 / yScale)
        }, completion: nil)
    }
    if context.previouslyFocusedView === self {
        coordinator.addCoordinatedAnimations({
            self.imgView.transform = .identity
        }, completion: nil)
    }
}

P.S。不要忘记在 UIImageView

上设置 clipsToBounds = false