Skip to content

Instantly share code, notes, and snippets.

@pcperini
Last active February 8, 2016 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcperini/d1b3f400c0b7b92d7027 to your computer and use it in GitHub Desktop.
Save pcperini/d1b3f400c0b7b92d7027 to your computer and use it in GitHub Desktop.
public protocol ConstraintStateMachineType: class {
// MARK: Types
typealias State: RawRepresentable
// MARK: Properties
var state: State? { get set }
var allConstraints: [NSLayoutConstraint] { get }
// MARK: Mutators
func setNeedsUpdateConstraints()
}
public extension ConstraintStateMachineType where State.RawValue == String {
// MARK: Properties
var state: State? {
get {
let constraints = self.allConstraints.flatMap { $0 as? StatefulConstraint }
let rawValue = constraints.filter { $0.priority == UILayoutPriorityDefaultHigh }
.first?.state ?? ""
return State(rawValue: rawValue)
}
set {
guard let state = newValue else { return }
let constraints = self.allConstraints.flatMap { $0 as? StatefulConstraint }
constraints.filter { $0.state != state.rawValue }
.forEach { $0.priority = UILayoutPriorityDefaultLow }
constraints.filter { $0.state == state.rawValue }
.forEach { $0.priority = UILayoutPriorityDefaultHigh }
self.setNeedsUpdateConstraints()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment