如何使NSTextView的高度始终高于20px的实际高度



我使用NSTextView作为文本编辑器,我想让它比用户输入文本后的重新计算高出大约20 PX。

也就是说,当NSTextView滚动到NSCrollView的末尾时,会有一个空白区域,这使得用户不必输入回车来创建空行。这样,尾部的文本将始终位于上侧,以方便用户的视觉体验。

你是怎么做到的?

如何根据内容调整NSTextView的大小?

我在这个问题中找到了一些提示,但连接太久后无效。

由于NSTextView大多数时候嵌套在NSScrolView中,因此可以使用滚动视图的边距。

下面的解决方案适用于基于故事板的应用程序,其最低要求为OS X 10.10(Yosemite(:

class ViewController: NSViewController {
@IBOutlet weak var scrollView: NSScrollView!
@IBOutlet weak var textView: NSTextView!
override func viewDidLoad() {
super.viewDidLoad()
textView.layoutManager?.delegate = self
scrollView.automaticallyAdjustsContentInsets = false
}
}
extension ViewController: NSLayoutManagerDelegate {
func layoutManager(_ layoutManager: NSLayoutManager, didCompleteLayoutFor textContainer: NSTextContainer?, atEnd layoutFinishedFlag: Bool) {
guard let textContainer = textContainer else { return }
let textRect = layoutManager.usedRect(for: textContainer)
let bottomSpace: CGFloat = 20.0
let bottomInset: CGFloat = (textRect.height + bottomSpace) > scrollView.bounds.height ? bottomSpace : 0
scrollView.contentInsets.bottom = bottomInset
scrollView.scrollerInsets.bottom = -bottomInset
}
}

编辑:如果单击底部空间,如何滚动文本视图

你可以玩NSParagraphStyle在最后一段后面加一些。或者,您可以使用响应程序链,使视图控制器将光标位置更改为文本视图的末尾:

class ViewController: NSViewController {
// ...
override func mouseUp(with event: NSEvent) {
let bottomSpace = scrollView.contentInsets.bottom
let clickLocation = self.view.convert(event.locationInWindow, to: textView)
let bottomRect = CGRect(x: 0, y: textView.bounds.height, width: textView.bounds.width, height: bottomSpace)
if bottomRect.contains(clickLocation) {
textView.moveToEndOfDocument(self)
}
}
}

如果您想要具有相同行为的多个文本视图,那么是时候设计自己的类了。

最新更新