ImageRectForBounds not called in subclass of NSButtonCell

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 
+4
source share
1 answer

With a little debugging, I understand that the default implementation of NSButtonCell does not call drawImage:withFrame:inView: What for? I can’t find an answer either on the forums or on the Apple docs (if someone explains, I will be happy :). I solved this problem by simply overriding drawImage:withFrame:inView: and calling imageRectForBounds: ::

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

Source: https://habr.com/ru/post/1446163/


All Articles