简体   繁体   中英

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:

在此处输入图片说明

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

Here's the view controller in IB:

在此处输入图片说明

How can I achieve vertical centering programatically?

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM