为NSTextView设置占位符字符串

时间:2015-04-03 08:13:26

标签: macos cocoa nstextview

有没有办法像NSTextView那样设置NSTextField的占位符字符串?我检查了房产,但找不到它。我搜索了一些问题,但没有正确的解释。

4 个答案:

答案 0 :(得分:10)

我在网上找到了这个答案。 Philippe Mougin做到了这一点。

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:@"This is my placeholder text" 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

答案 1 :(得分:10)

Swift 4

事实证明,placeholderAttributedString中的NSTextView属性似乎并未公开曝光。因此,您可以在自己的子类中实现它并获得默认的占位符行为(类似于NSTextField)。

class PlaceholderTextView: NSTextView {
     @objc var placeholderAttributedString: NSAttributedString?
}

如果将来可以使用此属性,则只需使用NSTextView而不是此子类。

答案 2 :(得分:6)

Swift 2.0

var placeHolderTitleString: NSAttributedString = NSAttributedString(string: "Place Holder Value", attributes: [NSForegroundColorAttributeName : NSColor.grayColor()])

override func becomeFirstResponder() -> Bool {
    self.needsDisplay = true
    return super.becomeFirstResponder()
}

override func drawRect(rect: NSRect) {
    super.drawRect(rect)

    if (self.string! == "") {
        placeHolderString.drawAtPoint(NSMakePoint(0, 0))
    }
}

答案 3 :(得分:1)

寻找这个。这可能是一个更好的方法!

localhost:8888