Question

How can i programatically space a UILabel element from the edges (equidistant)? I'm a bit stuck on this issue, as I've got no idea which property to call, or if it is a property I need. Is there anything auto layout can do for me?

Was it helpful?

Solution

Very easy, using this excellent autolayout category: https://github.com/jrturton/UIView-Autolayout

[self.yourLabel pinToSuperviewEdges:JRTViewPinLeftEdge|JRTViewPinRightEdge inset:20.0];

This pins the label 20 pixels from the left and right edges of its superview.

OTHER TIPS

With autolayout, you can center your label horizontally with:

label.translatesAutoresizingMaskIntoConstraints = NO;
[label addConstraint:[NSLayoutConstraint constraintWithItem:label
                                                  attribute:NSLayoutAttributeCenterX
                                                  relatedBy:NSLayoutRelationEqual
                                                     toItem:[label superview]
                                                  attribute:NSLayoutAttributeCenterX
                                                 multiplier:1 constant:0]];

Or with the format language you can fill the superview horizontally:

label.translatesAutoresizingMaskIntoConstraints = NO;
[label.addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@[@"H:|[label]|"] 
                                                              options:0 
                                                              metrics:nil
                                                                views:@{@"label":label}]];

Or center it:

label.translatesAutoresizingMaskIntoConstraints = NO;
[label.addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@[@"H:|-(>=0)-[label]-(>=0)-|"] 
                                                              options:0 
                                                              metrics:nil
                                                                views:@{@"label":label}]];

Or add a fixed margin on either side:

label.translatesAutoresizingMaskIntoConstraints = NO;
[label.addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@[@"H:|-(20)-[label]-(20)-|"] 
                                                              options:0 
                                                              metrics:nil
                                                                views:@{@"label":label}]];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top