CATextLayer 中的文本垂直居中

发布于 2024-10-20 05:42:40 字数 859 浏览 1 评论 0原文

我正在尝试使用约束在我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

热风软妹 2024-10-27 05:42:40

为了使图层的约束发挥作用,该图层的超级图层需要有一个布局管理器。因此,您需要执行 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文