【问题标题】:Subclassing NSButton, need to make it look like a regular button子类化 NSButton,需要让它看起来像一个普通的按钮
【发布时间】:2012-05-04 05:25:46
【问题描述】:

我将 NSButton 子类化,因为我需要在按住鼠标时重复选择器。

我是这样做的:

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
        [self setBezelStyle:NSBezelBorder];
        PotRightIsDown = NO;
    }

    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
    // Drawing code here.
}

- (void)mouseDown:(NSEvent *)theEvent;
{    
    NSLog(@"pot right mouse down");
    PotRightIsDown = YES;
    holdDownTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(sendCommand) userInfo:nil repeats:YES];
}

- (void)mouseUp:(NSEvent *)theEvent;
{
    NSLog(@"pot right mouse up");
    PotRightIsDown = NO;
}

-(void)sendCommand
{
    if (PotRightIsDown)
    {
        NSLog(@"run the stuff here");
    }
    else 
    {
        [holdDownTimer invalidate];
    }
}

像冠军一样工作,每 100 毫秒发送一次命令。

在 IB 的窗口中,我将斜角按钮拖到窗口上,并将其类设置为此子类。当我运行应用程序时,该按钮是不可见的,但它可以工作。我猜这是因为我在子类中有一个空的 drawRect 函数。

如何使这个子类按钮看起来像一个斜角按钮?

谢谢你,
有状态的

【问题讨论】:

  • [super drawRect:dirtyRect]?
  • 卡尔是对的,你需要写在-drawRect方法中。但我看到你使用-mouseDown-mouseUp 当按下左按钮不正确时调用它。如果您想要正确,您需要使用-rightMouseDown-rightMouseUp
  • 这很容易。谢谢你的提示,卡尔。请添加它作为答案,我会选中它。贾斯汀,鼠标左键是正确的。我之所以称它为 PotRight,是因为当你按住它时,它会将命令从串行端口发送到控制器,控制器将命令解释为我正在控制的物体上的电位计顺时针旋转。

标签: cocoa nsbutton


【解决方案1】:

如果您不向特定子类方法添加任何功能,那么您可以完全避免实现它,这将允许 超类 提供默认行为。

或者(正如我的@Carl Norum 指出的那样)您可以使用以下方法明确地做到这一点:

- (void)drawRect:(NSRect)dirtyRect
{
    [super drawRect:dirtyRect];
}

但这有点无意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 2013-06-28
    • 1970-01-01
    • 2017-01-19
    相关资源
    最近更新 更多