带有左对齐占位符的NSSearchField

时间:2017-08-12 02:09:02

标签: macos cocoa macos-sierra nssearchfield

设置centersPlaceholder = false后,占位符在左侧正确对齐,但搜索按钮不显示其图像。输入某些文本时取消按钮也是如此。这是正确的行为还是我错过了什么?

2 个答案:

答案 0 :(得分:2)

This related question阐明了奇怪的行为如何(ab)用于迫使场上的左对齐。只需子类化NSSearchFieldCell并覆盖draw方法:

import Cocoa

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

然后将搜索字段单元格设置为此类。

答案 1 :(得分:0)

#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

在xib文件中,将搜索类设置为AMSearchField