2009-09-04 69 views
2

我有一個CATextLayer,我希望能夠在我的視圖中垂直對齊。我可以設置一個約束來將它對齊到視圖的頂部,中間或底部;但我希望能夠讓用戶即時改變這一點。當我建立了我的CATextLayer,我用這個約束對齊,中間:如何更新CALayer的約束條件?

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

這工作得很好,但如果我想更新的層,將其調整到視圖頂部我嘗試:

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

當我添加新約束時,它不會與頂部對齊,而是越過視圖頂部,您只能看到它的一部分。它看起來像試圖應用這兩個約束。沒有removeConstraint,如果我在我的類上定義一個CAConstraint變量,並且在將它添加到CATextLayer後更新該變量,似乎會發生同樣的事情。我是否需要每次都重新創建CATextLayer?

回答

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