gpt4 book ai didi

swift - 如何让NSTextView的高度一直高于实际高度20px?

转载 作者:行者123 更新时间:2023-11-28 07:43:06 26 4
gpt4 key购买 nike

我正在使用 NSTextView 作为文本编辑器,我希望它比用户输入文本后重新计算的高度高约 20 PX。

也就是NSTextView在NSScrollView的末尾滚动的时候,有一个空白区域,使得用户不用输入return来做一个空白行。这样尾部的文字就会一直在上边,方便用户的视觉体验。

你是怎么做到的?

How to resize NSTextView according to its content?

我在这个问题中找到了一些提示,但是连接时间太长了。

最佳答案

由于您的 NSTextView 大多数时候都嵌套在 NSScrolView 中,因此您可以调整 ScrollView 的边距。

以下解决方案适用于基于 Storyboard的应用程序,它具有 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
}
}

编辑: 如果单击底部空间,如何滚动 TextView ?

你可以玩弄 NSParagraphStyle在最后一段之后添加一些。或者您可以使用响应链并使 View Controller 将光标位置更改为 TextView 的末尾:

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)
}
}
}

如果您想要具有相同行为的多个 TextView ,是时候设计您自己的类了。

关于swift - 如何让NSTextView的高度一直高于实际高度20px?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51695193/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com