我很困惑为什么这段代码不显示任何图像:
在app委托中:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSRect rect = window.frame;
rect.origin.x = 0;
rect.origin.y = 0;
BlueImageView *blueImageView = [[BlueImageView alloc]initWithFrame:rect];
window.contentView = blueImageView; // also tried [window.contentView addSubview: blueImageView];
}
Run Code Online (Sandbox Code Playgroud)
BlueImageView.h:
@interface BlueImageView : NSImageView {
}
@end
Run Code Online (Sandbox Code Playgroud)
BlueImageView.m:
@implementation BlueImageView
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setImage: [NSImage imageNamed:@"imagefile.png"]];
NSAssert(self.image, @"");
NSLog (@"Initialized");
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect {
}
@end
Run Code Online (Sandbox Code Playgroud)
文件imagefile.png存在.NSAssert不会导致异常.NSLog正在解雇.但窗口中没有图像显示.
调用drawRect:方法绘制视图,并立即返回实现.要让NSImageView为您绘制图像,请调用[super drawRect:dirtyRect];drawRect:的实现.如果您不打算在drawRect:中进行任何其他绘图,只需删除该方法以加快绘图速度.