Zei*_*ist 8 macos cocoa nstextview
有没有办法NSTextView像这样设置占位符字符串NSTextField?我检查了房产,但找不到它.我搜索了一些问题,但没有正确的解释.
Jan*_*ker 15
斯威夫特4
事实证明,似乎已经存在一个没有公开曝光的placeholderAttributedString财产NSTextView.因此,您可以在您自己的子类中简单地实现它并获得默认的占位符行为(类似于NSTextField).
class PlaceholderTextView: NSTextView {
@objc var placeholderAttributedString: NSAttributedString?
}
Run Code Online (Sandbox Code Playgroud)
如果将来可以使用此属性,则只需使用NSTextView而不是此子类.
sol*_*hin 11
我在网上找到了这个答案. 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
Run Code Online (Sandbox Code Playgroud)
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))
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
寻找这个。这可能是一个更好的方法!
final class CustomTextView: NSTextView {
private var placeholderAttributedString: NSAttributedString? = NSAttributedString(string: "Your placeholder string here")
private var placeholderInsets = NSEdgeInsets(top: 0.0, left: 4.0, bottom: 0.0, right: 4.0)
override func becomeFirstResponder() -> Bool {
self.needsDisplay = true
return super.becomeFirstResponder()
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
guard string.isEmpty else { return }
placeholderAttributedString?.draw(in: dirtyRect.insetBy(placeholderInsets))
}
}
extension NSRect {
func insetBy(_ insets: NSEdgeInsets) -> NSRect {
return insetBy(dx: insets.left + insets.right, dy: insets.top + insets.bottom)
.applying(CGAffineTransform(translationX: insets.left - insets.right, y: insets.top - insets.bottom))
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3583 次 |
| 最近记录: |