Mac OS 开发 NSTextView实现placeholderString功能

NSTextView并没有像TextField一样暴露placeholderString。但是我们可以子类化一个来实现功能。

//
//  TextViewWithPlaceHolder.m
//  easyVideo
//
//  Created by quanhao huang on 2019/12/19.
//  Copyright © 2019 easyVideo. All rights reserved.
//

#import "TextViewWithPlaceHolder.h"

static NSAttributedString *placeHolderString;
@implementation TextViewWithPlaceHolder

+ (void)initialize
{
  static BOOL initialized = NO;
    if (!initialized) {
        NSColor *txtColor = [NSColor grayColor];
        NSDictionary *txtDict = [NSDictionary dictionaryWithObjectsAndKeys:txtColor, NSForegroundColorAttributeName, nil];
        placeHolderString = [[NSAttributedString alloc] initWithString:@"发送消息..." attributes:txtDict];
    }
}

- (BOOL)becomeFirstResponder
{
    [self setNeedsDisplay:YES];
    return [super becomeFirstResponder];
}

- (void)drawRect:(NSRect)rect
{
    [super drawRect:rect];
    if ([[self string] isEqualToString:@""] && self != [[self window] firstResponder])
         [placeHolderString drawAtPoint:NSMakePoint(0,0)];
}

- (BOOL)resignFirstResponder
{
    [self setNeedsDisplay:YES];
    return [super resignFirstResponder];
}

@end

效果如下

发布了119 篇原创文章 · 获赞 4 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章