Vertically centering text in CATextLayer

I am trying to use contraint for the vertical center of the text in my CATextLayer, but the constraint does not seem to do anything. Is setting the constraint wrong or is there some other way that I have to do things for the vertical center of the 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 = [CAConstraintLayoutManager layoutManager];
[label addConstraint:[CAConstraint
                      constraintWithAttribute:kCAConstraintMidY
                      relativeTo:@"superlayer"
                      attribute:kCAConstraintMidY]];
[label setNeedsLayout];
[menuItemLayer addSublayer:label];
+3
source share
1 answer

In order for layer restrictions to work, there must be a layoutManager for the top-level layer. So you need to domenuItemLayer.layoutManager = [CAConstraintLayoutManager layoutManager];

The shortcut does not need its own layoutManager (if it does not have sublayers with applicable restrictions), so you can get rid of the line label.layoutManager = ....

+4
source

Source: https://habr.com/ru/post/1795984/


All Articles