gpt4 book ai didi

cocoa - 在自定义属性更改时重绘自定义 CALayer 子类

转载 作者:行者123 更新时间:2023-12-03 16:05:12 25 4
gpt4 key购买 nike

我正在尝试构建一个绘制文本的特殊图层。此 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 头文件中查找了 needDisplayForKey 的类方法定义,但在我看来,这是我想要使用的方法,还是我在这里遗漏了重要的一点?

来自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: 标记时,为什么我的图层没有重绘?

最佳答案

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;

关于cocoa - 在自定义属性更改时重绘自定义 CALayer 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10663746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com