如何更新CALayer上的约束?

时间:2009-09-04 12:30:02

标签: cocoa constraints calayer

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

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

这样可以正常工作,但是如果我想更新图层以将其对齐到视图的顶部我会尝试:

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

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

1 个答案:

答案 0 :(得分: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