Reputation: 4345
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?
Upvotes: 5
Views: 7120
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
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
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