为了使这个单独的文本容器工作,您将计算字符串每个部分的绘制大小并将 NSTextView 限制为该大小:
NSLayoutManager * layout = [[NSLayoutManager alloc] init];
NSString * storedString = @"A\nquick\nBrown\nFox";
NSTextStorage * storage = [[NSTextStorage alloc] initWithString:storedString];
[storage addLayoutManager:layout];
//I assume you have a parent view to add the text views
NSView * view;
//Assuming you want to split up into separate view by line break
NSArray * paragraphs = [storedString componentsSeparatedByString:@"\n"];
for (NSString * paragraph in paragraphs)
{
NSSize paragraphSize = [paragraph sizeWithAttributes:@{}];
//Create a text container only big enough for the string to be displayed by the text view
NSTextContainer * paragraphContainer = [[NSTextContainer alloc] initWithContainerSize:paragraphSize];
[layout addTextContainer:paragraphContainer];
//Use autolayout or calculate size/placement as you go along
NSRect lazyRectWithoutSizeOrPlacement = NSMakeRect(0, 0, 0, 0);
NSTextView * textView = [[NSTextView alloc] initWithFrame:lazyRectWithoutSizeOrPlacement
textContainer:paragraphContainer];
[view addSubview:textView];
}
您可以将委托添加到 NSLayoutManager 以查看您的文本容器使用情况:
- (void)layoutManager:(NSLayoutManager *)aLayoutManager
didCompleteLayoutForTextContainer:(NSTextContainer *)aTextContainer
atEnd:(BOOL)flag
{
if (aTextContainer == nil)
{
//All text was unable to be displayed in existing containers. A new NSTextContainer is needed.
}
}