首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自定义NSButtonCell,未调用drawBezelWithFrame

自定义NSButtonCell,未调用drawBezelWithFrame
EN

Stack Overflow用户
提问于 2013-05-30 22:12:29
回答 2查看 4.4K关注 0票数 1

我想知道如何在Cocoa/OSX中自定义绘制按钮。因为我的视图是自定义绘制的,所以我不会使用IB,而是想在代码中完成所有这些工作。我创建了NSButtonCell的子类和NSButton的子类。在NSButtonCell的子类中,我重写了方法drawBezelWithFrame:inView:,在我的子类NSButton的initWithFrame方法中,我使用setCell在按钮中设置我的CustomCell。然而,drawBezelWithFrame没有被调用,我不明白为什么。谁能指出我做错了什么,或者我在这里错过了什么?

NSButtonCell的子类:

代码语言:javascript
复制
#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的子类:

代码语言:javascript
复制
#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

用法:

代码语言:javascript
复制
- (void)addSendButton:(NSRect)btnSendRectRect 
{
    TWIButton *sendButton = [[TWIButton alloc] initWithFrame:btnSendRectRect];
    [self addSubview:sendButton];
    [sendButton setTitle:@"Send"];
    [sendButton setTarget:self];
    [sendButton setAction:@selector(send:)];
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-31 15:08:15

以下是您的代码中似乎遗漏的内容。

没有调用超级drawRect:dirtyRect

  • You不会覆盖从NSButton派生的类(
  1. )中的+ (类)cellClass

以下是修改后的代码:

代码语言:javascript
复制
@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处,并检查它是否会被调用。

票数 3
EN

Stack Overflow用户

发布于 2013-06-16 04:50:03

您可能会放弃Cell子类,因为看起来您只是使用它来实例化初始化器中的NSButton类型。简单地说

代码语言:javascript
复制
NSButton *button ...
[button setCell: [[TWIButtonCell alloc] init] autorelease]];

顺便说一句。在前面的示例中,您可能会有泄漏,因为您先初始化,然后调用可能有自己保留的setCell。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16838525

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档