为不带Cocoa绑定的NSTextView设置占位符字符串



我知道NSTextFieldNSTextView的"空占位符"可以在Cocoa绑定中设置。此外,对于NSTextField,占位符可以在Xcode接口生成器中设置,也可以与aTextField.placeholderString = ...一起设置。如果我不使用Cocoa绑定,如何设置NSTextView的占位符字符串?

NSTextView中的placeholderAttributedString属性未公开。因此,您可以简单地在自己的子类中实现它,并获得默认的占位符行为:

1-创建NSTextView 的子类

class CustomTextView: NSTextView {
            var placeholderAttributedString: NSAttributedString?
        }

2-在您的Viewcontroller 中使用

let attributes : [String : Any] = [NSFontAttributeName : NSFont(name: "HelveticaNeue-Light", size: 19)!, NSForegroundColorAttributeName : NSColor.green]
    yourTextView.placeholderAttributedString =  NSAttributedString(string: "Enter your Name", attributes: attributes)

最新更新