Skip to content

Instantly share code, notes, and snippets.

@steam
Created June 21, 2016 23:35
Show Gist options
  • Save steam/84ea0439d84ee8f6a52a1270a74846d0 to your computer and use it in GitHub Desktop.
Save steam/84ea0439d84ee8f6a52a1270a74846d0 to your computer and use it in GitHub Desktop.
/*
Experiment that animates a red square left to right in a container
by swapping the priority of the left and right layout constraints
*/
import UIKit
import XCPlayground
let container = UIView(frame: CGRectZero)
container.backgroundColor = .whiteColor()
container.translatesAutoresizingMaskIntoConstraints = false
let inner = UIView(frame: CGRectZero)
inner.translatesAutoresizingMaskIntoConstraints = false
inner.backgroundColor = .redColor()
container.addSubview(inner)
let innerWidth = NSLayoutConstraint(
item: inner,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1.0,
constant: 200)
let innerHeight = NSLayoutConstraint(
item: inner,
attribute: .Height,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1.0,
constant: 200)
let containerWidth = NSLayoutConstraint(
item: container,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1.0,
constant: 500)
let containerHeight = NSLayoutConstraint(
item: container,
attribute: .Height,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1.0,
constant: 500)
let top = NSLayoutConstraint(
item: inner,
attribute: .Top,
relatedBy: .Equal,
toItem: container,
attribute: .Top,
multiplier: 1.0,
constant: 50
)
let left = NSLayoutConstraint(
item: inner,
attribute: .Leading,
relatedBy: .Equal,
toItem: container,
attribute: .Leading,
multiplier: 1.0,
constant: 0
)
left.priority = 999
let right = NSLayoutConstraint(
item: inner,
attribute: .Trailing,
relatedBy: .Equal,
toItem: container,
attribute: .Trailing,
multiplier: 1.0,
constant: 0
)
right.priority = 998
NSLayoutConstraint.activateConstraints([
innerWidth,
innerHeight,
containerWidth,
containerHeight,
top,
left,
right
])
// animate the inner square left -> right -> left
// by swapping the left and right constraint priorities
func animate() {
UIView.animateWithDuration(1.0, animations: {
let prevRight = right.priority
let prevLeft = left.priority
left.priority = prevRight
right.priority = prevLeft
container.layoutIfNeeded()
}, completion: { if $0 { animate() }})
}
animate()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = container
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment