I needed to create an NSButton with an image and a name, but I did not like the standard positioning methods in cocoa.
I decided to subclass the button cell and override -imageRectForBounds: and -titleRectForBounds: to provide my custom positions. The problem is that the -titleRectForBounds: method is called normally, but -imageRectForBounds: not.
The images in the buttons are displayed normally, so the cell must have a frame to draw images that I just donβt know where it came from.
The code is really simple. For now, the only thing I have done is subclass NSButtonCell and override these two methods. Then in IB, I select NSButton and change my cell class to my own 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
source share