【问题标题】:How to make the height of NSTextView always higher than the actual height of 20px?如何让 NSTextView 的高度总是高于 20px 的实际高度?
【发布时间】:2018-08-05 14:26:45
【问题描述】:

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

即当NSTextView滚动到NSScrollView的末尾时,会有一个空白区域,让用户不用输入回车就可以做一个空行。这样尾巴的文字就会一直在上边,方便用户的视觉体验。

你是怎么做到的?

How to resize NSTextView according to its content?

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

【问题讨论】:

标签: swift macos cocoa nstextview


【解决方案1】:

由于您的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)
        }
    }
}

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

【讨论】:

  • 感谢您的回答。这有效地创建了一个空白区域,但是当我点击空白区域时,TextView的焦点不会在最后,这与原来的表现不同。有没有改进的可能?
猜你喜欢
  • 2018-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-09
  • 1970-01-01
  • 2010-09-06
相关资源
最近更新 更多