gpt4 book ai didi

cocoa - 如何更新 CALayer 上的约束?

转载 作者:行者123 更新时间:2023-12-03 16:39:44 29 4
gpt4 key购买 nike

我有一个 CATextLayer,我希望能够在我的 View 中垂直对齐。我可以设置一个约束将其与 View 的顶部、中间或底部对齐;但我希望能够允许用户即时更改此设置。当我设置 CATextLayer 时,我使用此约束将其在中间对齐:

[textLayer addConstraint: [CAConstraint constraintWithAttribute:kCAConstraintMidY
relativeTo:@"superlayer"
attribute:kCAConstraintMidY]];

这工作正常,但如果我想更新图层以将其与 View 顶部对齐,我会尝试:

[textLayer addConstraint: [CAConstraint constraintWithAttribute:kCAConstraintMaxY     
relativeTo:@"superlayer"
attribute:kCAConstraintMaxY]];

当我添加新约束时,它不会与顶部对齐,而是越过 View 的顶部,您只能看到它的一部分。看起来它正在尝试应用这两个约束。没有removeConstraint,如果我在类上定义 CAConstraint 变量并在将其添加到 CATextLayer 后更新该变量,似乎会发生同样的事情。我每次都需要重新创建 CATextLayer 吗?

最佳答案

看起来最好的方法是使用 CATextLayer 的 setConstraints 方法,并在我想要更改垂直对齐时替换所有约束。这就是我的代码现在的样子:

// Define the constraints for the class in the .h

@interface LayerView : NSView {

CATextLayer *textLayer;

CAConstraint *verticalConstraint;
CAConstraint *horizontalConstraint;
CAConstraint *widthConstraint;

}

- (IBAction)alignTextToTop:(id)sender;

@end

@implementation LayerView

- (id)initWithFrame:(NSRect)frameRect
{
id view = [super initWithFrame:frameRect];

horizontalConstraint = [CAConstraint constraintWithAttribute:kCAConstraintMidX relativeTo:@"superlayer" attribute:kCAConstraintMidX];

widthConstraint = [CAConstraint constraintWithAttribute:kCAConstraintWidth relativeTo:@"superlayer" attribute:kCAConstraintWidth];

verticalConstraint = [CAConstraint constraintWithAttribute:kCAConstraintMidY relativeTo:@"superlayer" attribute:kCAConstraintMidY];

[textLayer setConstraints:[NSArray arrayWithObjects:verticalConstraint, horizontalConstraint, widthConstraint, nil]];

return view;
}

// Update the constraints using setConstraints
- (IBAction)alignTextToTop:(id)sender
{
verticalConstraint = [CAConstraint constraintWithAttribute:kCAConstraintMaxY relativeTo:@"superlayer" attribute:kCAConstraintMaxY];

[textLayer setConstraints:[NSArray arrayWithObjects:verticalConstraint, horizontalConstraint, widthConstraint, nil]];
}

@end

关于cocoa - 如何更新 CALayer 上的约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1378931/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com