9

テキストを描画する特別なレイヤーを構築しようとしています。これTWFlapLayerには、プロパティとして属性付きの文字列があります。

TWFlapLayer.h:

@interface TWFlapLayer : CALayer
@property(nonatomic, strong) __attribute__((NSObject)) CFAttributedStringRef attrString;
@end

で合成されTWFlapLayer.mます:

@implementation TWFlapLayer

@synthesize attrString = _attrString;

/* overwrite method to redraw the layer if the string changed */

+ (BOOL)needsDisplayForKey:(NSString *)key
{
    if ([key isEqualToString:@"attrString"]){
        return YES;
    } else {
        return NO;
    }
}

- (void)drawInContext:(CGContextRef)ctx
{
    NSLog(@"%s: %@",__FUNCTION__,self.attrString);
    if (self.attrString == NULL) return;
    /* my custom drawing code */
}

私の意図は、合成されたセッターメソッドを使用して attrString プロパティが変更された場合、カスタム描画メソッドを使用してレイヤーが自動的に再描画されることでした。ただし、 drawInContext: メソッドに配置された NSLog ステートメントから、レイヤーが再描画されていないことがわかります。

needsDisplayForKey メソッドにブレークポイントを配置することで、attrString キーを要求されたときに YES が返されるようにしました。

私は今、このようにattrStringを変更しています

// self.frontString is a NSAttributedString* that is why I need the toll-free bridging
self.frontLayer.attrString = (__bridge CFAttributedStringRef) self.frontString;

//should not be necessary, but without it the drawInContext method is not called
[self.frontLayer setNeedsDisplay]; // <-- why is this still needed?

CALayer ヘッダー ファイルで needsDisplayForKey のクラス メソッド定義を調べましたが、これが私が使用したいメソッドのように思えますか、それともここで重要な点が抜けていますか?

からCALayer.h:

/* Method for subclasses to override. Returning true for a given
 * property causes the layer's contents to be redrawn when the property
 * is changed (including when changed by an animation attached to the
 * layer). The default implementation returns NO. Subclasses should
 * call super for properties defined by the superclass. (For example,
 * do not try to return YES for properties implemented by CALayer,
 * doing will have undefined results.) */

+ (BOOL)needsDisplayForKey:(NSString *)key;

概要

カスタム プロパティ attrString を変更して でマークすると、レイヤーが再描画されないのはなぜneedsDisplayForKey:ですか?

4

1 に答える 1

14

CALayer.hも言います:

/* CALayer implements the standard NSKeyValueCoding protocol for all
 * Objective C properties defined by the class and its subclasses. It
 * dynamically implements missing accessor methods for properties
 * declared by subclasses.

どうやらneedsDisplayForKey:メカニズムは、CALayer の動的に実装されたアクセサ メソッドに依存しているようです。したがって、これを変更します。

@synthesize attrString = _attrString;

@dynamic attrString;
于 2012-05-20T05:12:42.570 に答える