如何为tvOS聚焦元素设置约束条件

3
我在我的tvOS应用程序中有一个UICollectionView,其中包含一张图片和一段标题文本。我设置了一个约束条件,将标题文本固定在图片下方。

enter image description here

当单元格聚焦且图像变大时,文本不会移动并停留在图像上方。有没有一种方法可以设置一个约束条件,考虑到聚焦图像的尺寸?

Image without focus

Image with focus


我不明白你的意思。你想让焦点移动到图像上,此时标签是出现在图像底部还是覆盖在图像上? - Sankalap Yaduraj Singh
我想在图像聚焦时指定标签和图像之间的垂直间距。目前,只有在图像未聚焦时才能指定此间距。 - Jan
您可以在焦点上设置标签框架。 - Sankalap Yaduraj Singh
3个回答

8
您可以使用UIImageViewfocusedFrameGuide来实现这一功能。它返回一个UILayoutGuide对象,但很遗憾无法在Interface Builder中使用,但您可以在代码中使用它创建约束。请注意,此约束仅在视图被聚焦时才有意义,因此您必须根据self.focused属性设置其active属性。

首先,在视图初始化时创建约束:

self.focusedSpacingConstraint = NSLayoutConstraint(item: imageView.focusedFrameGuide, attribute: .BottomMargin, relatedBy: .Equal, toItem: label, attribute: .Top, multiplier: 1, constant: 0)
//add it to the view and set active to false

根据焦点情况,激活这个约束或默认约束中的一个:

override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
    coordinator.addCoordinatedAnimations({
  self.focusedSpacingConstraint.active = self.focused
  self.spacingConstraint.active = !self.focused

  //set label's transform and animate layout changes
}

您可以使用focusedFrameGuide来设置标签的高度(作为图像高度的百分比)。
这种方法的优点是,当图像大小改变时,您不必更改(硬编码的)constant

3

我最终将一个@IBOutlet设置为我的间距约束,并在didUpdateFocusInContext方法中更新它。为了增加一些效果,我还对标签进行了转换。

在我的集合单元格中:

override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
    coordinator.addCoordinatedAnimations({
        if self.focused {
            self.spacingConstraint.constant = 30
            UIView.animateWithDuration(0.3) {
                self.label.transform = CGAffineTransformMakeScale(1.15, 1.15)
                self.layoutIfNeeded()

            }
        }
        else {
            self.spacingConstraint.constant = 0
            UIView.animateWithDuration(0.3) {
                self.label.transform = CGAffineTransformMakeScale(1, 1)
                self.layoutIfNeeded()

            }
        }
        }, completion: nil)
}

0
请使用这段代码,希望它能帮到你。将此代码编写到自定义单元格类中。
override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
if (self.focused) {
   self.custom_ImageView.adjustsImageWhenAncestorFocused = true
   self.custom_LabelView1.frame = CGRectMake(0, 279, 548, 29)
}
else {
   self.custom_ImageView.adjustsImageWhenAncestorFocused = false
   self.custom_LabelView1.frame = CGRectMake(0, 259, 548, 29)
}
}

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