UIImageView
的focusedFrameGuide
来实现这一功能。它返回一个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
。我最终将一个@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)
}
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)
}
}