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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章