2015-04-03 99 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