使用CALayer委托 [英] Using CALayer Delegate

查看:109
本文介绍了使用CALayer委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UIView,其图层将有子图层。我想为每个子图层分配代理,因此委托方法可以告诉图层要绘制什么。我的问题是:

I have a UIView whose layers will have sublayers. I'd like to assign delegates for each of those sublayers, so the delegate method can tell the layer what to draw. My question is:

我应该提供什么作为CALayer的代表?文档说不要使用层所在的UIView,因为这是为视图的主CALayer保留的。但是,创建另一个类只是为了成为我创建的CALayers的代表,这就失败了不继承CALayer的目的。人们通常使用什么作为CALayer的代表?或者我应该只是子类?

What should I provide as CALayer's delegate? The documentation says not to use the UIView the layers reside in, as this is reserved for the main CALayer of the view. But, creating another class just to be the delegate of the CALayers I create defeats the purpose of not subclassing CALayer. What are people typically using as the delegate for CALayer? Or should I just subclass?

另外,为什么实现委托方法的类不必遵循某种CALayer协议?这是一个我不太了解的更广泛的首要问题。我认为所有需要实现委托方法的类都需要一个协议规范,以便实现者遵守。

Also, why is it that the class implementing the delegate methods doesn't have to conform to some sort of CALayer protocol? That's a wider overarching question I don't quite understand. I thought all classes requiring implementation of delegate methods required a protocol specification for implementers to conform to.

推荐答案

最轻的解决方案会要在文件中创建一个小助手类作为使用CALayer的UIView:

The lightest-wight solution would be to create a small helper class in the the file as the UIView that's using the CALayer:

在MyView.h中

@interface MyLayerDelegate : NSObject
. . .
@end

在MyView.m中

@implementation MyLayerDelegate
- (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)ctx
{
. . .
}
@end

只需将它们放在文件的顶部,紧接在#import指令下面。这样,感觉更像是使用私有类来处理绘图(虽然它不是 - 委托类可以通过任何导入标题的代码实例化)。

Just place those at the top of your file, immediately below the #import directives. That way it feels more like using a "private class" to handle the drawing (although it isn't -- the delegate class can be instantiated by any code that imports the header).

这篇关于使用CALayer委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆