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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With