我需要创建一个同时包含图像和标题的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发布于 2013-12-14 19:03:37
据我所知,通过很少的调试,默认的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];
}https://stackoverflow.com/questions/13393922
复制相似问题