2015-04-03 100 views
8

有什么办法可以像NSTextField那样设置NSTextView的占位符字符串吗?我已经检查过该物业但找不到它。我搜查了一些问题,但没有一个正确的解释。设置NSTextView的占位符字符串

回答

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 
6

雨燕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)) 
    } 
} 
+0

这是超级有用,但有关如何使占位符文本换行多行的任何想法? – 2017-03-12 02:44:41

7

斯威夫特4

事实证明,有似乎已经成为一个NSTextViewplaceholderAttributedString属性未公开曝光。因此,您可以简单地在自己的子类中实现它并获取默认的占位符行为(类似于NSTextField)。

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

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

+2

我已经提出了一个要求苹果公开此属性的雷达http://www.openradar.me/33583675 ​​ – 2017-07-28 04:16:42

+0

这似乎并不奏效。我在一个子类中实现了属性,但不显示它。 – Austin 2017-10-28 17:49:00

+0

@JanApotheker是的,目前还不确定它是在swift4还是在10.13。这不起作用 – 2017-10-29 10:36:41