I needed to create a NSButton with both image and title but I didn't like any of the standard positioning methods in cocoa.
I decided to subclass the button cell and override the -imageRectForBounds:
and -titleRectForBounds:
to provide my custom positions. The problem is that the -titleRectForBounds:
method gets called normally but the -imageRectForBounds:
is not.
The images in the buttons are shown normally so the cell must have a frame to draw the images I just don't know where it gets it from.
The code is really simple. At the moment the only thing I did is to subclass NSButtonCell and override those two methods. Then in IB I choose an NSButton and change its cell class to my custom button cell.
Here is the code:
#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
With little debugging I understand, that default NSButtonCell
implementation doesn't calls drawImage:withFrame:inView:
. Why? I don't find an answer neither on forums nor at the Apple docs (If someone explain - I will be happy :). I was solve this issue by simply override drawImage:withFrame:inView:
and call imageRectForBounds:
:
- (void)drawImage:(NSImage *)image withFrame:(NSRect)frame inView:(NSView *)controlView
{
[super drawImage:image withFrame:[self imageRectForBounds:frame] inView:controlView];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With