NSSearchField with left aligned placeholder

478 Views Asked by At

After setting centersPlaceholder = false, the placeholder aligns correctly at the left, but the search button doesn't show its image. The same is true for the cancel button when entering some text. Is that the correct behavior or am I missing something?

2

There are 2 best solutions below

1
sbenitezb On BEST ANSWER

This related question sheds some light on how the strange behavior could be (ab)used to force a left-align in the field. Simply subclass NSSearchFieldCell and override draw method:

import Cocoa

class FilterFieldCell: NSSearchFieldCell {
    override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
        super.draw(withFrame: cellFrame, in: controlView)
    }
}

And then set your search field cell to this class.

0
JasonHan On
#define kSearchButtonWidth 22.f

#import "AMSearchField.h"

@implementation AMSearchField

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];
    // Drawing code here.
}

- (NSRect)rectForSearchButtonWhenCentered:(BOOL)isCentered
{
    CGRect rect = [super rectForSearchButtonWhenCentered:isCentered];
    if (rect.size.width < kSearchButtonWidth) {
        rect.size.width = kSearchButtonWidth;
    }
    return rect;
}

- (NSRect)rectForSearchTextWhenCentered:(BOOL)isCentered
{
    CGRect rect = [super rectForSearchTextWhenCentered:isCentered];
    if (rect.origin.x < kSearchButtonWidth) {
        CGFloat delta = kSearchButtonWidth - rect.origin.x;
        rect.origin.x = kSearchButtonWidth;
        rect.size.width = rect.size.width - delta;
    }
    return rect;
}

@end

in xib file, set search class to AMSearchField