3

我的UICollectionViewtvOS 应用程序中有一个图像和标题文本。我已经设置了一个约束来将标题文本固定在图像下方。

在此处输入图像描述

当单元格聚焦并且图像增长时,文本不会移动并停留在图像上。有没有办法设置一个考虑到聚焦图像大小的约束?

没有焦点的图像

带焦点的图像

4

3 回答 3

8

您可以为此使用UIImageView属性focusedFrameGuide。它返回一个UILayoutGuide对象,遗憾的是不能在 Interface Builder 中使用,但您可以在代码中使用它创建约束。注意这个约束只有在视图被聚焦时才有意义,所以你必须active根据属性来设置它的self.focused属性。

首先创建视图初始化的约束:

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在图像大小发生变化时更改(硬编码)。

于 2016-02-25T21:23:59.260 回答
2

我最终设置了@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)
}
于 2016-02-15T10:25:32.823 回答
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)
}
}
于 2016-02-15T08:54:51.693 回答