我有自己的最小 View 类:
- (void) awakeFromNib
{
NSLog(@"awakeFromNib!");
[self.layer setDelegate:self];
[self.layer setFrame:CGRectMake(30, 30, 250, 250)];
self.layer.masksToBounds = YES;
self.layer.cornerRadius = 5.0;
self.layer.backgroundColor = [[UIColor redColor] CGColor];
[self setNeedsDisplay];
}
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
NSLog(@"drawing!");
}
drawLayer:inContext 永远不会被调用,尽管我可以将图层视为红色圆角矩形。我错过了什么?
编辑:来自苹果文档
You can draw content for your layer, or better encapsulate setting the layer’s content image by creating a delegate class that implements one of the following methods: displayLayer: or drawLayer:inContext:.
Implementing a delegate method to draw the content does not automatically cause the layer to draw using that implementation. Instead, you must explicitly tell a layer instance to re-cache the content, either by sending it a setNeedsDisplay or setNeedsDisplayInRect: message, or by setting its needsDisplayOnBoundsChange property to YES.
还有
drawLayer:inContext:
If defined, called by the default implementation of drawInContext:.
最佳答案
您永远不应该更改 UIView 层的委托(delegate)。来自 UIView 图层属性的文档:
Warning: Since the view is the layer’s delegate, you should never set the view as a delegate of another CALayer object. Additionally, you should never change the delegate of this layer.
如果你想在 View 中进行自定义绘图,只需重写drawRect:方法即可。
如果您确实想使用图层,则需要创建自己的图层:
UIView *myView = ...
CALayer *myLayer = [CALayer layer];
myLayer.delegate = self;
[myView.layer addSublayer:myLayer];
在这两种情况下,您都需要在第一种情况下在 View 上调用 setNeedsDisplay,在第二种情况下在自定义图层上调用 setNeedsDisplay。你永远不会直接调用drawRect:或drawLayer:inContext:,它们会在你调用setNeedsDisplay时自动调用。
关于iphone - 绘制层 :inContext is not called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4033811/