在NSButtonCell子类中未调用imageRectForBounds

Jac*_*opo 5 macos cocoa objective-c nsbutton nsbuttoncell

我需要创建一个同时带有图像和标题的NSButton,但是我不喜欢可可中的任何标准定位方法。

我决定对按钮单元进行子类化,并覆盖-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
Run Code Online (Sandbox Code Playgroud)

Lex*_*ndr 2

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

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