Writing iOS Layout Constraints The Easy Way

  • Hansmartin Geiser

Coming from a web-development background, native iOS development always feels a bit clunky to me when it comes to creating the layouts.

Yes, there is the Interface Builder and it is a great tool, but sometimes,

things get more generic and building the views and layouts can be more efficiently done by hand.

Except – layout constraints! Writing layout constraints can be tedious work.

Example, making an element the half of the width of its parent element in objective-c:

[self.view addSubview:centerView];

// Width constraint, half of parent view width
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:centerView
                               attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual
                               toItem:self.view attribute:NSLayoutAttributeWidth
                               multiplier:0.5 constant:0]];

It is not much better in C# with Xamarin either:

View.AddSubview(centerView);

// Width constraint, half of parent view width
View.AddConstraint(
    NSLayoutConstraint.Create(centerView, 
        NSLayoutAttribute.Width, NSLayoutRelation.Equal, 
        View, NSLayoutAttribute.Width, 
        0.5f, 0f
   )
);

But behold! There is our ConstraintHelper!

ConstraintHelper.Attach(centerView).WidthOfParent(0.5f).Top().Center();

The ConstraintHelper is a small C# library to help with the layout constraints and it brings less common concepts like Method Chaining to the layout constraints.

ConstraintHelper is Open Source and can be forked from GitHub.


Qu’en pensez-vous?