views:

323

answers:

1

I have a CATextLayer that I want to be able to vertically align within 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 be able to allow the user to change this on the fly. When I set up my CATextLayer, I use this constraint to align it in the middle:

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

This works fine, 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 the new constraint it doesn't get aligned to the top, but goes past the top of the view where you can only see part of it. It looks like it is trying to apply both of the constraints. There is no removeConstraint and the same thing seems to happen if I define a CAConstraint variable on my class and just update that variable after adding it to the CATextLayer. Do I need to recreate the CATextLayer every time?

A: 

Looks like the best way to do this was to use the setConstraints method of the CATextLayer and replace all the constraints whenever I wanted to change the vertical alignment. This is now 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
Austin