Created
November 16, 2015 01:12
-
-
Save tkersey/11aecfaf38bfc89493a6 to your computer and use it in GitHub Desktop.
Calculate preferred height of UIView
This file contains hidden or 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
extension UIView { | |
func calculatePreferredHeight(preferredWidth: CGFloat? = nil) -> CGFloat { | |
let width = preferredWidth ?? frame.width | |
let widthConstraint = NSLayoutConstraint.constraintsWithVisualFormat("H:[view(==\(width)@999)]", options: .allZeros, metrics: nil, views: ["view": self]) | |
addConstraints(contraint) | |
let height = systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height | |
removeConstraints(constraint) | |
return height | |
} | |
} |
Thanks, here is an updated version:
func calculatePreferredHeight(preferredWidth: CGFloat) -> CGFloat {
let widthConstraint = NSLayoutConstraint(
item: self,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: preferredWidth
)
addConstraint(widthConstraint)
let height = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
removeConstraint(widthConstraint)
return height
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!