NSTextField的单元格setPlaceholderAttributedString - 获得焦点时占位符不可见

时间:2013-03-05 10:15:54

标签: objective-c cocoa

我使用setPlaceholderAttributedString:对象的NSTextFieldCell来设置具有自定义字体和颜色的占位符。这是整个代码......

_statusMessageField = [[NSTextField alloc] initWithFrame:NSZeroRect];
[_statusMessageField setBordered:NO];
[_statusMessageField setBezeled:NO];
[_statusMessageField setFocusRingType:NSFocusRingTypeNone];
[_statusMessageField setDrawsBackground:NO];
[_statusMessageField setTextColor:TM_NS_COLOR(35, 37, 46)];
[_statusMessageField setFont:[NSFont systemFontOfSize:13.0]];

NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:@"What's up?"];
NSRange range = NSMakeRange( 0, [placeholder length] );
[placeholder addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:13.0] range:range];
[placeholder addAttribute:NSForegroundColorAttributeName value:TM_NS_COLORA( 92, 97, 114, 0.7 ) range:range];
[placeholder fixAttributesInRange:range];
[_statusMessageField.cell setPlaceholderAttributedString:placeholder];
_statusMessageField.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:_statusMessageField];

......它让我发疯,因为......

    仅当NSTextField没有焦点时,
  • 占位符才可见
  • 当我点击NSTextField时,插入符号可见,没有输入任何内容,但占位符消失,这是错误的,应该可见,直到输入至少一个字符为止,

...当我将setPlaceholderAttributedString:替换为setPlaceholderString:(无归因)时,占位符行为正确 - 当NSTextField没有焦点或焦点没有输入时,可见。

知道什么是错的吗?

此处是图片http://d.pr/i/WoC9的链接,您可以在其中看到差异。

1 个答案:

答案 0 :(得分:0)

我认为您需要在NSTextField状态下选中“拒绝第一响应者”框。

这将解决问题。

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    [_statusMessageField setBordered:NO];
    [_statusMessageField setBezeled:NO];
    [_statusMessageField setFocusRingType:NSFocusRingTypeNone];
    [_statusMessageField setDrawsBackground:NO];
    [_statusMessageField setTextColor:[NSColor blueColor]];
    [_statusMessageField setFont:[NSFont systemFontOfSize:13.0]];

    NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:@"What's up?"];
    NSRange range = NSMakeRange( 0, [placeholder length] );
    [placeholder addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:13.0] range:range];
    [placeholder addAttribute:NSForegroundColorAttributeName value:[NSColor greenColor] range:range];
    [placeholder fixAttributesInRange:range];
    [_statusMessageField.cell setPlaceholderAttributedString:placeholder];
    _statusMessageField.translatesAutoresizingMaskIntoConstraints = NO;
    [_statusMessageField setRefusesFirstResponder:NO];


}

- (void)awakeFromNib {

    [_statusMessageField setRefusesFirstResponder:YES];
}

此致 尼拉姆