我试图弄清楚如何在Cocoa / OSX中自定义绘制按钮。由于我的视图是自定义绘制的,因此我不会使用IB,而是希望在代码中全部完成。我创建了NSButtonCell的子类和NSButton的子类。在NSButtonCell的子类中,我重写方法drawBezelWithFrame:inView:;在子类NSButton的initWithFrame方法中,我使用setCell在Button中设置CustomCell。但是,drawBezelWithFrame没有被调用,我不明白为什么。有人可以指出我做错了什么或我在这里错过了什么吗?
NSButtonCell的子类:
#import "TWIButtonCell.h"
@implementation TWIButtonCell
-(void)drawBezelWithFrame:(NSRect)frame inView:(NSView *)controlView
{
//// General Declarations
[[NSGraphicsContext currentContext] saveGraphicsState];
//// Color Declarations
NSColor* fillColor = [NSColor colorWithCalibratedRed: 0 green: 0.59 blue: 0.886 alpha: 1];
//// Rectangle Drawing
NSBezierPath* rectanglePath = [NSBezierPath bezierPathWithRect: NSMakeRect(8.5, 7.5, 85, 25)];
[fillColor setFill];
[rectanglePath fill];
[NSGraphicsContext restoreGraphicsState];
}
@end
NSButton的子类:
#import "TWIButton.h"
#import "TWIButtonCell.h"
@implementation TWIButton
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
TWIButtonCell *cell = [[TWIButtonCell alloc]init];
[self setCell:cell];
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect
{
// Drawing code here.
}
@end
用法:
- (void)addSendButton:(NSRect)btnSendRectRect
{
TWIButton *sendButton = [[TWIButton alloc] initWithFrame:btnSendRectRect];
[self addSubview:sendButton];
[sendButton setTitle:@"Send"];
[sendButton setTarget:self];
[sendButton setAction:@selector(send:)];
}
最佳答案
以下是您的代码中似乎缺少的东西。
您没有在调用[super drawRect:dirtyRect]
您不会在派生自NSButton的Class(TWIButton)中覆盖+(Class)cellClass。
以下是更改后的代码:
@implementation TWIButton
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
TWIButtonCell *cell = [[TWIButtonCell alloc]init];
[self setCell:cell];
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect
{
// Drawing code here.
//Changes Added!!!
[super drawRect:dirtyRect];
}
//Changes Added!!!!
+ (Class)cellClass
{
return [TWIButtonCell class];
}
@end
现在将断点保持在drawBezelWithFrame处,并检查它是否会被调用。