Skip to content

Instantly share code, notes, and snippets.

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 colbylwilliams/2484e2e83356871134db399f81f767ae to your computer and use it in GitHub Desktop.
Save colbylwilliams/2484e2e83356871134db399f81f767ae to your computer and use it in GitHub Desktop.
public static void ConstrainToParentCenter(this UIView view, nfloat height = default(nfloat), nfloat width = default(nfloat))
{
if (view?.Superview == null) throw new InvalidOperationException("Must add view to a superview before calling this method");
view.TranslatesAutoresizingMaskIntoConstraints = false;
var verticalFormat = string.Format("V:[super]-(<=1)-[view{0}]", height == default(nfloat) ? string.Empty : $"({height})");
var horizontalFormat = string.Format("H:[super]-(<=1)-[view{0}]", width == default(nfloat) ? string.Empty : $"({width})");
var viewsAndMetrics = new object [] { "super", view.Superview, "view", view };
view.Superview.AddConstraints(NSLayoutConstraint.FromVisualFormat(verticalFormat, NSLayoutFormatOptions.AlignAllCenterX, viewsAndMetrics));
view.Superview.AddConstraints(NSLayoutConstraint.FromVisualFormat(horizontalFormat, NSLayoutFormatOptions.AlignAllCenterY, viewsAndMetrics));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment