First, make sure that translatesAutoresizingMaskIntoConstraints set to NO if you are creating the label programmatically.
The first limitation you need is "label.trailing = superview.trailing".
[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeTrailing multiplier:1.f constant:0.f]
This will snap the right edge (left to right) to the label on the right edge of the supervisor.
Now you need a constraint for position Y
In my test, I vertically centered the label with the following restriction:
[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeCenterY multiplier:1.f constant:0.f]
Now comes the trick!
Each time you change the text on the shortcut, you need to recalculate frames using AutoLayout.
[superview setNeedsLayout]; [superview layoutIfNeeded];
Autostart will be:
1) Set a new size label (based on its text).
2) Adjust the size of the mark.
3) Connect the trailing edge of the label to the trailing edge of the supervisor.
Further research
The problem with UILabel is that when you use AutoLayout and you set the text, its intrinsicContentSize changes, but does not start the layout update.
The way to enforce this without subclassing UILabel is to use Objective-C runtime.
@interface UILabel (AutoLayout) - (void)swz_setText:(NSString*)text; @end @implementation UILabel (AutoLayout) + (void)load { NSLog(@"Swizzling [UILabel setFont:]..."); Method oldMethod = class_getInstanceMethod(self, @selector(setText:)); Method newMethod = class_getInstanceMethod(self, @selector(swz_setText:)); method_exchangeImplementations(oldMethod, newMethod); } - (void)swz_setText:(NSString*)text { if (![text isEqualToString:self.text]) { [self setNeedsLayout]; } [self swz_setText:text];
In this category, I improve the implementation of setText: by calling setNeedsLayout if the text changes.
Now you just need to call layoutIfNeeded in the supervision to recount / rebuild the label frame.
Click here for the playground (Swift 2.0 - Xcode 7) where I checked my code.
Hope this helps.