Skip to content

Instantly share code, notes, and snippets.

@tkersey
Created November 16, 2015 01:12
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tkersey/11aecfaf38bfc89493a6 to your computer and use it in GitHub Desktop.
Save tkersey/11aecfaf38bfc89493a6 to your computer and use it in GitHub Desktop.
Calculate preferred height of UIView
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
}
}
@TheMoon2000
Copy link

Thank you!

@TomaszPietrowski
Copy link

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