sbenitezb
sbenitezb

Reputation: 535

NSSearchField with left aligned placeholder

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?

Upvotes: 2

Views: 480

Answers (2)

JasonHan
JasonHan

Reputation: 1

#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

Upvotes: 0

sbenitezb
sbenitezb

Reputation: 535

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.

Upvotes: 2

Related Questions