Skip to content

Instantly share code, notes, and snippets.

@oliver-foggin
Last active September 21, 2017 06:41
Show Gist options
  • Save oliver-foggin/7ef9e2b7f77b733ea0afb782d7c7d7e0 to your computer and use it in GitHub Desktop.
Save oliver-foggin/7ef9e2b7f77b733ea0afb782d7c7d7e0 to your computer and use it in GitHub Desktop.
Animating a basic layout with UIStackView
import UIKit
import PlaygroundSupport
class RoundView: UIView {
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.height * 0.5
}
}
let containerView: UIView = {
let v = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 600))
v.backgroundColor = UIColor(white: 0.95, alpha: 1)
return v
}()
let headerView: UIView = {
let v = UIView()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = UIColor(white: 0.8, alpha: 1)
return v
}()
let roundView: RoundView = {
let v = RoundView()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .red
v.clipsToBounds = true
v.heightAnchor.constraint(equalTo: v.widthAnchor).isActive = true
return v
}()
let label: UILabel = {
let l = UILabel()
l.translatesAutoresizingMaskIntoConstraints = false
l.text = "Hello, world!"
l.setContentHuggingPriority(UILayoutPriorityDefaultLow, for: .horizontal)
return l
}()
let button: UIButton = {
let b = UIButton(type: .custom)
b.translatesAutoresizingMaskIntoConstraints = false
b.setTitle("Press", for: .normal)
b.backgroundColor = .green
b.heightAnchor.constraint(equalToConstant: 30).isActive = true
b.widthAnchor.constraint(equalToConstant: 70).isActive = true
return b
}()
let stackView: UIStackView = {
let s = UIStackView(arrangedSubviews: [roundView, label, button])
s.translatesAutoresizingMaskIntoConstraints = false
s.axis = .vertical
s.spacing = 10
s.alignment = .center
s.layoutMargins = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
s.isLayoutMarginsRelativeArrangement = true
return s
}()
containerView.addSubview(headerView)
headerView.addSubview(stackView)
let roundViewHeightConstraint = roundView.heightAnchor.constraint(equalToConstant: 80)
NSLayoutConstraint.activate([
headerView.topAnchor.constraint(equalTo: containerView.topAnchor),
headerView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
headerView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
stackView.topAnchor.constraint(equalTo: headerView.topAnchor),
stackView.bottomAnchor.constraint(equalTo: headerView.bottomAnchor),
stackView.leadingAnchor.constraint(equalTo: headerView.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: headerView.trailingAnchor),
roundViewHeightConstraint,
])
PlaygroundPage.current.liveView = containerView
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
stackView.axis = .horizontal
roundViewHeightConstraint.constant = 60
UIView.animate(withDuration: 0.5) {
containerView.layoutIfNeeded()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment