我正试图在我的CATextLayer中使用约束来垂直居中文本,但约束似乎没有做任何事情。约束设置是否错误或是否有其他方式我应该做垂直居中文本的事情?
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];
答案 0 :(得分:4)
要使图层的约束起作用,图层的超层需要有一个layoutManager。因此,您需要执行menuItemLayer.layoutManager = [CAConstraintLayoutManager layoutManager];
标签不需要自己的layoutManager(除非它有应用约束的子图层),所以你可以摆脱label.layoutManager = ...
行。