I'm trying to use a contraint to vertically center text in my CATextLayer but the constraint doesn't seem to be doing anything. Is the constraint setup wrong or is there some other way I should be doing things to vertically center text?
CATextLayer *label = [[CATextLayer alloc] init];
NSRect labelRect;
labelRect.origin.x = 20;
labelRect.origin.y = 0;
labelRect.size.width = width - 40;
labelRect.size.height = height;
[label setFont:@"Helvetica-Bold"];
[label setFontSize: fontSize];
[label setFrame:labelRect];
[label setString:[NSString stringWithFormat:@"Menu Item %d", i]];
[label setAlignmentMode:kCAAlignmentLeft];
[label setForegroundColor:whiteColor];
label.layoutManager = [CAConstraintLayou开发者_开发问答tManager layoutManager];
[label addConstraint:[CAConstraint
constraintWithAttribute:kCAConstraintMidY
relativeTo:@"superlayer"
attribute:kCAConstraintMidY]];
[label setNeedsLayout];
[menuItemLayer addSublayer:label];
For a layer's constraints to work, the layer's superlayer needs to have a layoutManager. So, you'll need to do menuItemLayer.layoutManager = [CAConstraintLayoutManager layoutManager];
The label doesn't need its own layoutManager (unless it has sublayers with constraints applied), so you can get rid of the label.layoutManager = ...
line.
精彩评论