TIL: Adding identifiers to NSLayoutConstraints helps troubleshoot broken constraint messages

Jonathan_MoosekianJonathan_Moosekian USUniversity ✭✭

I've been developing a pretty complex layout using AutoLayout, and tend to define my constraints in code like this:

_mainView.TopAnchor.ConstraintEqualTo(_topView.BottomAnchor).Active = true;
_mainView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor).Active = true;
_mainView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor).Active = true;
_mainView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor).Active = true;

But if the layout can't be satisfied, I end up seeing broken layout constraint messages in my Application output. The problem I was having is that I couldn't tell which constraints were the ones related to the ones posted above.

That's when I learned I could set an identifier on the constraints themselves, and that identifier would be printed along with the constraints in the broken constraints message.

But how do I set the identifier on constraints like the above without having to first set it to a variable, and then set the Identifier property to some meaningful value, like this?

var topAnchorConstraint = _mainView.TopAnchor.ConstraintEqualTo(_topView.BottomAnchor);
topAnchorConstraint.SetIdentifier("myView_TopAnchor_To_topView_BottomAnchor");
topAnchorConstraint.Active = true;

I created a helpful extension method like this:

public static NSLayoutConstraint WithIdentifier(this NSLayoutConstraint constraint, string identifier)
{
    constraint.SetIdentifier(identifier);
    return constraint;
}

So, now I can easily give identifiers to my constraints like this:

_mainView.TopAnchor.ConstraintEqualTo(_topView.BottomAnchor).WithIdentifier("myView_TopAnchor_To_topView_BottomAnchor").Active = true;

And if the constraint can't be satisfied, I see output similar to this in my Application Output now:

<NSLayoutConstraint:0x7f8316ee7d30 'myView_TopAnchor_To_topView_BottomAnchor' V:[UIView:0x7f8316ef6b80(0)]>

I hope this helps others out there when dealing with broken layout constraints. I debated posting this here, since it isn't a question or discussion, so if anyone knows a good place to post this info, let me know.

Sign In or Register to comment.