Adding padding to the "left" text box

I have a text box with a background, but for it to look right, the text box should have some addition on the left side, a bit like NSSearchField. How can I overlay the text box on the pad to the left ?

+3
source share
2 answers

Use customizable NSTextFieldCell, which redefines drawingRectForBounds: . Let it insert a rectangle as many as you like, and then pass a new rectangle [super drawingRectForBounds:] to get the normal fill and return the result of this call.

+7
source

smorgan , , , - setBorder:YES .

, , :

#import <Foundation/Foundation.h>
// subclass NSTextFieldCell
@interface InstructionsTextFieldCell : NSTextFieldCell {        
}
@end

#import "InstructionsTextFieldCell.h"

@implementation InstructionsTextFieldCell

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here. (None needed.)
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (NSRect)drawingRectForBounds:(NSRect)rect {

    // This gives pretty generous margins, suitable for a large font size.
    // If you're using the default font size, it would probably be better to cut the inset values in half.
    // You could also propertize a CGFloat from which to derive the inset values, and set it per the font size used at any given time.
    NSRect rectInset = NSMakeRect(rect.origin.x + 10.0f, rect.origin.y + 10.0f, rect.size.width - 20.0f, rect.size.height - 20.0f);
    return [super drawingRectForBounds:rectInset];

}

// Required methods
- (id)initWithCoder:(NSCoder *)decoder {
    return [super initWithCoder:decoder];
}
- (id)initImageCell:(NSImage *)image {
    return [super initImageCell:image];
}
- (id)initTextCell:(NSString *)string {
    return [super initTextCell:string];
}
@end

(, , , , , , , .x.)

, , awakeFromNib /, :

// Assign the textfield a customized cell, inset so that text doesn't run all the way to the edge.
InstructionsTextFieldCell *newCell = [[InstructionsTextFieldCell alloc] init];
[newCell setBordered:YES]; // so background color shows up
[newCell setBezeled:YES];
[self.tfSyncInstructions setCell:newCell];
[newCell release];
+9

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


All Articles