Last active
August 29, 2015 14:18
-
-
Save ibru/7471d51ff53863b317d9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use this NSLayoutConstraint subclass to specify it's constant to have relative value of screen width or height.