James Harpe
James Harpe

Reputation: 4345

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?

Upvotes: 5

Views: 7120

Answers (3)

jrturton
jrturton

Reputation: 119242

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.

Upvotes: 2

tylerd
tylerd

Reputation: 51

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]];

Upvotes: 3

Omarj
Omarj

Reputation: 1159

try to reaching the UIlabel height after center it ???

or u can reallocate the label location at your custom cell in programatically.

Upvotes: 0

Related Questions