CATextLayer 中的文本垂直居中
我正在尝试使用约束在我的 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];
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 = [CAConstraintLayoutManager layoutManager];
[label addConstraint:[CAConstraint
constraintWithAttribute:kCAConstraintMidY
relativeTo:@"superlayer"
attribute:kCAConstraintMidY]];
[label setNeedsLayout];
[menuItemLayer addSublayer:label];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了使图层的约束发挥作用,该图层的超级图层需要有一个布局管理器。因此,您需要执行
menuItemLayer.layoutManager = [CAConstraintLayoutManager layoutManager];
标签不需要自己的布局管理器(除非它具有应用了约束的子层),因此您可以摆脱
label.layoutManager = ...
行。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.