为了在我的 UIView 子类中保留层委托方法,我使用了一个基本的重新委托委托类。该类无需定制即可重复使用,避免了子类化 CALayer 或创建单独的委托类仅用于图层绘制的需要。
@interface LayerDelegate : NSObject
- (id)initWithView:(UIView *)view;
@end
使用此实现:
@interface LayerDelegate ()
@property (nonatomic, weak) UIView *view;
@end
@implementation LayerDelegate
- (id)initWithView:(UIView *)view {
self = [super init];
if (self != nil) {
_view = view;
}
return self;
}
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context {
NSString *methodName = [NSString stringWithFormat:@"draw%@Layer:inContext:", layer.name];
SEL selector = NSSelectorFromString(methodName);
if ([self.view respondsToSelector:selector] == NO) {
selector = @selector(drawLayer:inContext:);
}
void (*drawLayer)(UIView *, SEL, CALayer *, CGContextRef) = (__typeof__(drawLayer))objc_msgSend;
drawLayer(self.view, selector, layer, context);
}
@end
图层名称用于允许每个图层的自定义绘制方法。例如,如果您为图层分配了名称,例如layer.name = @"Background";
,那么您可以实现如下方法:
- (void)drawBackgroundLayer:(CALayer *)layer inContext:(CGContextRef)context;
请注意,您的视图将需要对此类的实例进行强引用,并且它可以用作任意数量的层的委托。
layerDelegate = [[LayerDelegate alloc] initWithView:self];
layer1.delegate = layerDelegate;
layer2.delegate = layerDelegate;