Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios 6: Center UILabel vertically using Auto Layout constraints

I have a UILabel I sometimes want to center vertically in a cell. This has to be done programatically. I've tried adding the following constraint to center it (locName is the UILabel):

[cell addConstraint:[NSLayoutConstraint constraintWithItem:cell
attribute:NSLayoutAttributeCenterY relatedBy:0 toItem:cell.locName 
attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];

This is the result I get:

enter image description here

It looks like its centering, but maybe changing the height of the UILabel or something?

Here's the view controller in IB:

enter image description here

How can I achieve vertical centering programatically?

like image 229
James Harpe Avatar asked Oct 08 '12 12:10

James Harpe


2 Answers

How about this: In addition to your centering constraint, add a height constraint for cell.locName to make it taller.

[cell.contentView addConstraint:
    [NSLayoutConstraint constraintWithItem:cell.locName
                                 attribute:NSLayoutAttributeHeight
                                 relatedBy:NSLayoutRelationGreaterThanOrEqual
                                    toItem:nil
                                 attribute:NSLayoutAttributeNotAnAttribute
                                multiplier:1
                                  constant:20]];
like image 145
tylerd Avatar answered Sep 30 '22 01:09

tylerd


You are probably hitting the other constraints already in place in the cell. Adding constraints doesn't make the other constraints go away - if you have spacing between the top and bottom labels, for example, to satisfy this and the new centring constraint, the height of the top label will have to shrink.

You may need to make outlets for these other constraints and remove them to achieve the centred design.

like image 32
jrturton Avatar answered Sep 29 '22 23:09

jrturton