Skip to content

Instantly share code, notes, and snippets.

@getaclue00
Created August 10, 2018 16:31
Show Gist options
  • Save getaclue00/148e32722a19521144b06ca6f924cd78 to your computer and use it in GitHub Desktop.
Save getaclue00/148e32722a19521144b06ca6f924cd78 to your computer and use it in GitHub Desktop.
Padding Custom Margins In NSTextField
//
// PaddedNSTextField.swift
// reference - https://stackoverflow.com/a/38138336
import Cocoa
class PaddedNSTextFieldCell: NSTextFieldCell {
@IBInspectable var leftPadding: CGFloat = 8.0
override func drawingRect(forBounds rect: NSRect) -> NSRect {
let rectInset = NSMakeRect((rect.origin.x + leftPadding), (rect.origin.y + leftPadding), (rect.size.width - leftPadding), (rect.size.height - leftPadding))
return super.drawingRect(forBounds: rectInset)
}
}
////////// OTHER FROM: http://burnignorance.com/objective-c-development-tips/padding-custom-margins-in-nstextfield/ ////
Create a Class say CustomTextFieldCell inheriting NSTextFieldCell.
@interface CustomTextFieldCell : NSTextFieldCell
@end
Override functions of NSTextFieldCell class as follows
@implementation CustomTextField
//Function will create rect for title
//Any padding implemented in this function will be visible in title of textfieldcell
- (NSRect)titleRectForBounds:(NSRect)theRect
{
NSRect titleFrame = [super titleRectForBounds:theRect];
//Padding on left side
titleFrame.origin.x = PADDING_MARGIN;
//Padding on right side
titleFrame.size.width -= (2 * PADDING_MARGIN);
return titleFrame;
}
//Any padding implemented in this function will be visible while editing text in textfieldcell
//If Padding is not done here, padding done for title will not be visible while editing
- (void)editWithFrame:(NSRect)aRect inView:(NSView *)controlView editor:(NSText *)textObj delegate:(id)anObject event:(NSEvent *)theEvent
{
NSRect textFrame = aRect;
textFrame.origin.x += PADDING_MARGIN;
textFrame.size.width -= (2* PADDING_MARGIN);
[super editWithFrame: textFrame inView: controlView editor:textObj delegate:anObject event: theEvent];
}
//Any padding implemented in this function will be visible while selecting text in textfieldcell
//If Padding is not done here, padding done for title will not be visible while selecting text
- (void)selectWithFrame:(NSRect)aRect inView:(NSView *)controlView editor:(NSText *)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength
{
NSRect textFrame = aRect;
textFrame.origin.x += PADDING_MARGIN;
textFrame.size.width -= (2* PADDING_MARGIN);
[super selectWithFrame: textFrame inView: controlView editor:textObj delegate:anObject start:selStart length:selLength];
}
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
{
NSRect titleRect = [self titleRectForBounds:cellFrame];
[[selfattributedStringValue] drawInRect:titleRect];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment