【问题标题】:imageRectForBounds not called in NSButtonCell subclassNSButtonCell 子类中未调用 imageRectForBounds
【发布时间】:2012-11-03 20:10:10
【问题描述】:

我需要创建一个包含图像和标题的 NSButton,但我不喜欢 cocoa 中的任何标准定位方法。

我决定继承按钮单元格并覆盖-imageRectForBounds:-titleRectForBounds: 以提供我的自定义位置。问题是-titleRectForBounds: 方法被正常调用但-imageRectForBounds: 不是。

按钮中的图像正常显示,因此单元格必须有一个框架来绘制我只是不知道它从哪里得到的图像。

代码非常简单。目前我唯一做的就是继承 NSButtonCell 并覆盖这两个方法。然后在 IB 中,我选择一个 NSButton 并将其单元格类更改为我的自定义按钮单元格。

代码如下:

#import "JSButtonCell.h"

@implementation JSButtonCell

- (NSRect)titleRectForBounds:(NSRect)theRect
{
    NSLog(@"Bounds for title");
    NSLog(@"%@",NSStringFromRect(theRect));
    NSRect titleRect = [super titleRectForBounds:theRect];
    NSLog(@"Title rect");
    NSLog(@"%@",NSStringFromRect(titleRect));
    return titleRect;
}

- (NSRect)imageRectForBounds:(NSRect)theRect
{
    NSLog(@"Bounds for image");
    NSLog(@"%@",NSStringFromRect(theRect));
    NSRect imageRect = [super imageRectForBounds:theRect];
    NSLog(@"Image rect");
    NSLog(@"%@",NSStringFromRect(imageRect));
    imageRect.origin.y -= 20;
    return imageRect;
}

@end

【问题讨论】:

  • 这里也发生了同样的事情。你有没有发现发生了什么?
  • 不,很抱歉我刚刚放弃了这种方法。
  • 好的,谢谢你告诉我。我会回来发布解决方案 - 如果我找到一个......

标签: objective-c macos cocoa nsbutton nsbuttoncell


【解决方案1】:

据我所知,只需少量调试,默认的NSButtonCell 实现不会调用drawImage:withFrame:inView:。为什么?我在论坛和 Apple 文档中都找不到答案(如果有人解释 - 我会很高兴 :)。我通过简单地覆盖drawImage:withFrame:inView: 并调用imageRectForBounds: 来解决这个问题:

- (void)drawImage:(NSImage *)image withFrame:(NSRect)frame inView:(NSView *)controlView
{
    [super drawImage:image withFrame:[self imageRectForBounds:frame] inView:controlView];
}

【讨论】:

    猜你喜欢
    • 2013-05-26
    • 2010-12-18
    • 2018-05-17
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    相关资源
    最近更新 更多