Search code examples
objective-cxcode7nslayoutconstraint

Strange NSLayoutConstraint Behavior


I have a UIScrollView that I add a UITextView to. I have the following constraint that I am also adding to the view:

NSLayoutConstraint *xConstraint = [NSLayoutConstraint constraintWithItem:textView2 attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:_scrollView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:50];

This constraint works perfectly but changing it from leading to trailing like so, has no effect. It still displays based on the leading.

NSLayoutConstraint *xConstraint = [NSLayoutConstraint constraintWithItem:textView2 attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:_scrollView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:50];

I have no understanding why the UITextView's location doesn't change position when I change the constraint from leading to trailing. I realize that I would also need to change 50 to -50 if it was constraining to the trailing edge, but it isn't.


Solution

  • The solution to this turned out to be to insert a UIView inside of the UIScrollView. I did this in the storyboard, and set the top and bottom constraints for the UIView to the UIScrollView, but I set the leading and trailing constraints for the UIView to the parent View that contains the UIScrollView that in turn contains the UIView. This allows the leading and trailing constraints to function correctly.