swift之NSTextView的使用
fileprivate let tv:NSTextView = {
let textView = NSTextView(frame: NSMakeRect(30, 30, 200, 30))
return textView
}();
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.addSubview(self.tv);
//1设置textStorage的代理,实现NSTextStorageDelegate代理协议的textStorageDidProcessEiting方法
//实现响应用户输入
tv.textStorage?.delegate = self;
/***
textStorage存储富文本
**/
let attributedString = NSMutableAttributedString(string: "attringbutedString" as String)
attributedString.addAttributes([NSAttributedString.Key.foregroundColor : NSColor.green as Any], range: NSMakeRange(0, 5))
attributedString.addAttributes([NSAttributedString.Key.font : NSFont(name: "宋体", size: 14) as Any], range: NSMakeRange(5, 10))
tv.textStorage?.setAttributedString(attributedString)
}
//实现NSTextStorageDelegate代理协议的textStorageDidProcessEiting方法
func textStorage(_ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int) {
//文本框高度根据文字高度自适应增长
self.perform(#selector(self.setHeightToMatchContents), with: nil, afterDelay: 0.0)
}
//计算当前输入文本的高度
func naturalSize()->NSSize {
let bounds:NSRect = self.tv.bounds;
let layoutManager:NSLayoutManager = self.tv.textStorage!.layoutManagers[0]
let textContainer:NSTextContainer = layoutManager.textContainers[0]
textContainer.containerSize = NSMakeSize(bounds.size.width, 1.0e7)
layoutManager.glyphRange(for: textContainer)
let naturalSize: NSSize? = layoutManager.usedRect(for: textContainer).size
return naturalSize!
}
//根据文本高度修改文本框对应的滚动条高度
@objc func setHeightToMatchContents() {
let naturalSize: NSSize = self.naturalSize()
if let scrollView = self.tv.enclosingScrollView {
let frame = scrollView.frame
scrollView.frame = NSMakeRect(frame.origin.x, frame.origin.y, frame.size.width, naturalSize.height + 4)
}
}
}