3

I have a UILabel object in my UIView. I want to let this lable moving respectively when its super view size changes. This is like the old UIViewAutoresizingFlexibleTopMargin, UIViewAutoresizingFlexibleRightMargin, UIViewAutoresizingFlexibleBottomMargin and UIViewAutoresizingFlexibleLeftMargin, so that if the superview height changed, the label top margin would change respectively, and the same for left margin.

How to do this with Autolayout not the old autoresizingmask?

Ahmed Said
  • 1,285
  • 5
  • 16
  • 28
  • If the top margin should change is the bottom margin fixed? In this case you only have to add a constraint which defines the bottom margin. – dasdom Dec 21 '13 at 15:40
  • I want all the four margins move respectively like the old behavior – Ahmed Said Dec 21 '13 at 15:51
  • @dasdom I set a bottom constraint to stick a subview to the bottom of a view controller's view, but the subview jumps up & down during rotation. But, with `UIViewAutoresizingFlexibleTopMargin`, the subview stays pinned to the bottom of its superview during rotation. I guess I'll just stick with `autoresizingMask`. – ma11hew28 Jun 22 '14 at 13:14

1 Answers1

1

You use the multiplier property of the NSLayoutConstraint to achieve this. You can't mix edge attributes with size attributes, but you can use the bottom and right edges as proxies for size.

UIView * parent = [[UIView alloc] init];

UILabel * label = [[UILabel alloc] init];

[parent addSubview:label];
[label setTranslatesAutoresizingMaskIntoConstraints:NO];

//Label top stays at 20% of the height of the view
NSLayoutConstraint * topMargin = [NSLayoutConstraint constraintWithItem:label
                                                              attribute:NSLayoutAttributeTop 
                                                              relatedBy:NSLayoutRelationEqual
                                                                 toItem:parent
                                                              attribute:NSLayoutAttributeBottom
                                                             multiplier:0.2f
                                                               constant:0.0f];
[parent addConstraint:topMargin];
Fruity Geek
  • 7,351
  • 1
  • 32
  • 41