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

我的意图是,如果使用合成的 setter 方法更改了 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 回答