如何按宽度拆分NSAttributedString?

时间:2013-05-28 13:00:03

标签: macos cocoa nsattributedstring

我有一个给定的视宽宽度(例如450,我从viewWidth = rectOftable.size.width;获得),其中rectOftable是一个矩形,内容视图的大小(宽度和高度)。现在,我创建了一个NSAttributedString,其中包含一个字符串,其大小可能大于450(例如1100)。

我需要做的是将此NSAttributedString拆分为相对于给定宽度的多个子字符串(此处为450,即视图的大小)。所以,这里需要显示1100/450 = 2 + 1行。

目前,我所能做的只是按长度拆分NSAttributedString,即[attrStr attributedSubstringFromRange:NSMakeRange(startIndex, 170)]其中170这里是当前的长度,但是大小是1100.

如何将宽度分割NSAttributedString?关于此,没有任何参考。

2 个答案:

答案 0 :(得分:1)

以下是使用NSTextContainer(例如[NSTextView textContainer])的方法:

// remember the orginal values
BOOL widthTracksTextView = [textContainer widthTracksTextView];
BOOL heightTracksTextView = [textContainer heightTracksTextView];
NSSize containerSize = [textContainer containerSize];
CGFloat lineFragmentPadding = [textContainer lineFragmentPadding];

// set these as we need them
[textContainer setWidthTracksTextView:NO];
[textContainer setHeightTracksTextView:NO];
[textContainer setContainerSize:screenFrame.size];
[textContainer setLineFragmentPadding:0.0];

// this cause glyph generation and layout
(void) [textView.layoutManager glyphRangeForTextContainer:textContainer];

// return the size that the view would need to be in order to display
// all the glyphs that are currently laid into the container
NSRect layoutRect = [textView.layoutManager usedRectForTextContainer:textContainer];
layoutRect.size.width = ceil(layoutRect.size.width);
layoutRect.size.height = ceil(layoutRect.size.height);

// restore orginal values
[textContainer setContainerSize:containerSize];
[textContainer setWidthTracksTextView:widthTracksTextView];
[textContainer setHeightTracksTextView:heightTracksTextView];
[textContainer setLineFragmentPadding:lineFragmentPadding];

答案 1 :(得分:0)

你问的是一个复杂的问题;什么可以适合给定的空间取决于字体,字体大小和其他因素,所有这些因素可能会随NSAttributedString的长度而变化。这就是OS X提供处理所有内容的类的原因;请参阅NSTextViewNSTextNSLayoutManager

你真的需要自己打破文本吗?如果没有,那么使用提供的类。如果是,那么你有一些阅读要做!