How do I update the limit on my CALayer?

I have a CATextLayer that I want to be able to vertically align in my view. I can set a constraint to align it to the top of the view, to the middle, or to the bottom; but I want to allow the user to change this on the fly. When I customize my CATextLayer, I use this constraint to align it in the middle:

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

      

This works great, but if I want to update the layer to align it to the top of the view, I try:

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

      

When I add a new constraint, it is not top-aligned but goes past the top of the view, where you can only see part of it. It looks like it is trying to enforce both constraints. There is no removeConstraint, and it seems to happen if I define a CAConstraint variable in my class and just update that variable after adding it to the CATextLayer. Do I need to recreate the CATextLayer every time?

+2


source to share


1 answer


It looks like the best way to do this is to use the setConstraints method of the CATextLayer and replace all the constraints when I want to change the vertical alignment. This is what my code looks like:



// 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

      

+2


source







All Articles