3

代码示例

我在自定义(不是 TextView)中有一个NSLayoutManager, NSTextContainer & NSTextStorageas 属性,初始化如下:NSViewawakeFromNib()

    textStorage = NSTextStorage(attributedString: self.attributedString)

    layoutManager = NSLayoutManager()
    textContainer = NSTextContainer(containerSize: NSMakeSize(self.frame.size.width, 1))

    layoutManager.addTextContainer(textContainer)
    textStorage.addLayoutManager(layoutManager)
    layoutManager.glyphRangeForTextContainer(textContainer)

故意将其垂直设置containerSizeNSTextContainer1,以查看它是否具有隐藏正在呈现的文本的预期效果 - 它没有!在视图中呈现此文本没有任何区别 - 这是问题的主题

drawRect我包括下面的行来绘制文本:

let glyphRange = layoutManager.glyphRangeForTextContainer(textContainer)
self.lockFocus()
layoutManager.drawGlyphsForGlyphRange(glyphRange, atPoint: NSMakePoint(0, 0))
self.unlockFocus()

发现

  1. 最好在翻转坐标系中使用您的自定义视图,就像NSTextView我觉得我将进入一个痛苦的世界一样!不管怎样, NSLayoutManager 总是开始在一个翻转的坐标系统内部绘制它的文本(就像NSTextView
  2. containerSize.width属性NSTextContainer具有以下效果:它在所有级别(包括第一个级别)的行级别上绑定(我知道这很明显,但坚持我......)
  3. containerSize.height属性NSTextContainer有一个曲线球:即使包含的视图没有空间垂直显示它,它也不会绑定在第一行但将绑定到后续行

*我花了很长时间才得出这个假设,containerSize.height因为我只画了一条线!*

问题

  1. 我的结论是否NSTextContainer正确?
  2. 从垂直角度控制文本绘制的最佳方法是什么?我想将我的单行文本放在视图的底部(而不是像默认情况下那样浮动在顶部)
4

1 回答 1

2

NSTextContainer有财产containerSize。布局管理器正在布局该容器内的文本。据推测,容器在您的视图中逻辑上位于 (0, 0) 处,但文本从其顶部开始布局。所以,容器有松弛。

您可以根据从返回的矩形调整容器的-[NSLayoutManager usedRectForTextContainer:]大小以使其适合。


更新:

我认为像这样的代码drawRect()应该适用于您想要实现的目标:

layoutManager.ensureLayoutForTextContainer(textContainer)
var rect = layoutManager.usedRectForTextContainer(textContainer)
rect.origin.x += 2
rect.origin.y = NSMaxY(self.bounds) - NSHeight(rect) - 4

let glyphRange = layoutManager.glyphRangeForTextContainer(textContainer)
layoutManager.drawGlyphsForGlyphRange(glyphRange, atPoint:rect.origin)
于 2015-03-11T18:36:07.480 回答