1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
#import "NSTextFieldCell+Inset.h"
#import <AppKit/AppKit.h>
#import <objc/runtime.h>
@interface NSTextFieldCell ()
@property NSSize textInset;
- (bool)_isEditingInView:(NSView *)view;
@end
@implementation NSTextFieldCell (Inset)
- (void)setTextInset:(NSSize)textInset
{
objc_setAssociatedObject(self, @selector(textInset), @(textInset), OBJC_ASSOCIATION_RETAIN);
}
- (NSSize)textInset
{
return [objc_getAssociatedObject(self, _cmd) sizeValue];
}
- (void)drawWithFrameHook:(NSRect)cellFrame inView:(NSView *)controlView
{
NSSize inset = self.textInset;
if (self.drawsBackground) {
[self.backgroundColor setFill];
if ([self _isEditingInView:controlView]) {
NSRectFill(cellFrame);
}
else {
NSRectFill(NSMakeRect(cellFrame.origin.x, cellFrame.origin.y,
cellFrame.size.width, inset.height));
NSRectFill(NSMakeRect(cellFrame.origin.x, cellFrame.origin.y + cellFrame.size.height - inset.height,
cellFrame.size.width, inset.height));
NSRectFill(NSMakeRect(cellFrame.origin.x, cellFrame.origin.y + inset.height,
inset.width, cellFrame.size.height - inset.height * 2));
NSRectFill(NSMakeRect(cellFrame.origin.x + cellFrame.size.width - inset.width, cellFrame.origin.y + inset.height,
inset.width, cellFrame.size.height - inset.height * 2));
}
}
cellFrame.origin.x += inset.width;
cellFrame.origin.y += inset.height;
cellFrame.size.width -= inset.width * 2;
cellFrame.size.height -= inset.height * 2;
[self drawWithFrameHook:cellFrame inView:controlView];
}
+ (void)load
{
method_exchangeImplementations(class_getInstanceMethod(self, @selector(drawWithFrame:inView:)),
class_getInstanceMethod(self, @selector(drawWithFrameHook:inView:)));
}
@end
@implementation NSTextField (Inset)
- (bool)wantsUpdateLayerHook
{
CGSize inset = ((NSTextFieldCell *)self.cell).textInset;
if (inset.width || inset.height) return false;
return [self wantsUpdateLayerHook];
}
+ (void)load
{
Method method = class_getInstanceMethod(self, @selector(wantsUpdateLayer));
if (class_addMethod(self, @selector(wantsUpdateLayer), method_getImplementation(method), method_getTypeEncoding(method))) {
method = class_getInstanceMethod(self, @selector(wantsUpdateLayer));
}
method_exchangeImplementations(method,
class_getInstanceMethod(self, @selector(wantsUpdateLayerHook)));
}
@end
|