You can use a UIImageView
property focusedFrameGuide
for that. It returns a UILayoutGuide
object, which unfortunately can't be used in Interface Builder, but you can create constraints with it in code. Note that this constraint makes sense only when the view is focused, so you have to set its active
property according to the self.focused
property.
First create the constraint on view initialization:
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
Then activate either this constraint or the default one depending on the focus:
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
}
You can also use the focusedFrameGuide
to set label's height (as a percentage of image's height).
The advantage of this approach is that you don't have to change the (hardcoded) constant
whenever the image size changes.