Skip to content

Instantly share code, notes, and snippets.

@ibru
Last active August 29, 2015 14:18
Show Gist options
  • Save ibru/7471d51ff53863b317d9 to your computer and use it in GitHub Desktop.
Save ibru/7471d51ff53863b317d9 to your computer and use it in GitHub Desktop.
class RelativeLayoutConstraint: NSLayoutConstraint {
enum RelativeMetric {
case None
case ScreenWidth
case ScreenHeight
}
@IBInspectable var percentage: CGFloat = 0
// Unfortuately, enums are not yet supported as IBInspectables. We have to use booleans for each enum case
/*@IBInspectable*/ var metric: RelativeMetric = .None
@IBInspectable var screenWidth: Bool = false {
didSet {
if screenWidth { metric = .ScreenWidth }
}
}
@IBInspectable var screenHeight: Bool = false {
didSet {
if screenHeight { metric = .ScreenHeight }
}
}
override var constant: CGFloat {
get {
if metric != .None {
let value = maximumValueFor(metric) * percentage / 100.0
return value
}
return super.constant
}
set {
super.constant = newValue
metric = .None // if 'constant' property is set explicitly, give it the priority against percentage value
}
}
private func maximumValueFor(metric: RelativeMetric) -> CGFloat {
switch metric {
case .ScreenWidth:
return UIScreen.mainScreen().bounds.width
case .ScreenHeight:
return UIScreen.mainScreen().bounds.height
case .None:
return 0
}
}
}
@ibru
Copy link
Author

ibru commented Apr 1, 2015

You can use this NSLayoutConstraint subclass to specify it's constant to have relative value of screen width or height.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment