我想弄清楚如何在Cocoa/OSX中自定义绘制按钮。因为我的视图是自定义绘制的,我不会使用IB,并希望在代码中完成这一切。我创建了NSButtonCell的一个子类和NSButton的一个子类。在NSButtonCell的子类中,我重写了方法drawBezelWithFrame:inView:并且在我的子类NSButton的initWithFrame方法中,我使用setCell来设置按钮中的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]
- 你没有重写+(类)cellClass在类(TWIButton)派生自NSButton
@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并检查它是否会被调用
一个人可能会放弃NSButton子类,因为它看起来像你只使用它在初始化器中实例化Cell类型。简单的
NSButton *button ...
[button setCell: [[TWIButtonCell alloc] init] autorelease]];
顺便说一句。你可能会在前面的例子中有一个泄漏,因为你初始化,然后调用setCell,可能有自己的保留。