NSView子类-drawRect:未调用 [英] NSView subclass - drawRect: not called
问题描述
我创建了一个名为 DAView
的 NSView
子类,其中包含了一系列有用的方法供以后重用。这很好用,但是 drawRect:
绝不会在使用 DAView
的任何类中或在类本身中被调用。为什么?
I have created a NSView
subclass called DAView
, incorporating an array of useful methods for later re-use. This works great, however, drawRect:
is never called in any classes that use DAView
, nor in the class itself. Why?
这是 DAView
的样子:
DAView
@interface DAView:NSView
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
self.backgroundColor = [NSColor clearColor];
// Make layer-backed by default
self.wantsLayer = YES;
// Create a root layer
CALayer *_rootLayer = [CALayer layer];
_rootLayer.shouldRasterize = YES;
_rootLayer.name = DAViewRootLayerDefaultName;
self.layer = _rootLayer;
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect // never called
{
NSLog(@"Draw Rect called");
}
现在,如果我想利用此 DAView的
附加方法/方法,我遇到了同样的问题。一切正常,除了 drawRect:
,就像在 DAView
的情况下一样,永远不会调用它:
Now, if I wanted to make use of this DAView's
additions/methods, I face the same problem. Everything works fine, except for drawRect:
, which, as in DAView
's case, is never called:
DATableView
@interface DATableView:DAView
- (void)drawRect:(NSRect)dirtyRect // never called either
{
[[NSColor grayColor] set];
NSBezierPath *_cellSeparator = [NSBezierPath bezierPath];
[_cellSeparator lineToPoint:dirtyRect.origin];
[_cellSeparator closePath];
[_cellSeparator stroke];
NSLog(@"Draw rect");
}
但是如果我更改 DATableView
的标题是 NSView
的子类,调用 drawRect:
。
我缺少什么?
However If I change DATableView
's header to be a subclass of NSView
, drawRect:
is called.
What am I missing?
推荐答案
您必须设置 _rootLayer code>到
self
。
you have to set the delegate of _rootLayer
to self
.
编辑
对我如何工作:
EDIT How it works for me:
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.wantsLayer = YES;
self.layer = [self makeBackingLayer];
[self.layer setDelegate:self];
}
return self;
}
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
NSRect rect = self.bounds;
rect.origin.x = 0;
rect.origin.y = 0;
[self drawRect:rect];
}
这篇关于NSView子类-drawRect:未调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!