Cocoa - NSMenuItem 中的自定义 NSView 将不会绘制
我有一个自定义 NSView,它曾经在 NIB 中创建并分配为 NSMenuItem 的视图,效果很好,但现在我想在代码中创建视图(有充分的理由我可以向你保证),这看起来并不难但视图实际上并不是在绘制。
即使我发送“setNeedsDisplay:”消息,之前在需要时调用以绘制视图的“drawRect:”消息也不再被调用。
我用图像初始化视图并设置视图的大小(视图的大小以匹配图像大小),这似乎有效,因为菜单项的大小正确,但没有图像。
这里可能发生什么?
这是初始化视图的代码:
-(id)initWithImage:(NSImage*)image
{
self = [super init];
if (self != nil)
{
self.imageToDisplay = image;
// this bit does get called and resizes the view to match the image size
NSRect imageBounds = NSMakeRect(0.0f, 0.0f, imageToDisplay.size.width, imageToDisplay.size.height);
[self setBounds:imageBounds];
[self setFrame:imageBounds];
[self setHidden:NO];
[self setAlphaValue:1.0f];
[self setAutoresizesSubviews:YES];
}
return self;
}
这是用于绘制不会被调用的视图的代码
// this is never called
-(void)drawRect:(NSRect)dirtyRect
{
if (imageToDisplay == nil)
return;
NSRect imageBounds = NSMakeRect(0.0f, 0.0f, imageToDisplay.size.width, imageToDisplay.size.height);
[self setBounds:imageBounds];
[self setFrame:imageBounds];
[imageToDisplay drawInRect:[self bounds]
fromRect:imageBounds
operation:NSCompositeSourceAtop
fraction:1.0f];
}
这是添加视图的菜单项的代码。
-(void)awakeFromNib
{
MyCustomView* view = [[MyCustomView alloc] init];
[self setView:view];
// i would have expected the image to get drawn at this point
[view setNeedsDisplay:YES];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须先设置视图的
frame
,然后才能设置其bounds
。在您的-init...
中,交换两个set...
调用,或者删除setBounds:
(bounds< /code> 默认情况下设置为
{(0,0), (frame.size.width, frame.size.height)}
)并且一切都应该正常。我也不认为你需要在drawRect
中再次设置frame
和bounds
,事实上,改变它似乎是一个坏主意当焦点已经锁定在您的视图上时;如果值实际上不同,充其量只会导致奇怪的闪烁。更新:刚刚在 查看编程指南:
You have to set your view's
frame
before you can set itsbounds
. In your-init...
, either swap the twoset...
calls, or remove thesetBounds:
(bounds
is set to{(0,0), (frame.size.width, frame.size.height)}
by default anyways) and everything should work. I also don't think that you need to setframe
andbounds
again indrawRect
, and in fact it seems like a bad idea to change those when focus is already locked on your view; at best it will cause weird flashing if the values are actually different.UPDATE: just saw this note in the View Programming Guide: