2

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

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

这很好用,但如果我想更新图层以将其与视图顶部对齐,我尝试:

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

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

4

1 回答 1

2

看起来最好的方法是使用 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
于 2009-09-07T00:08:05.403 回答