Apple 有一篇关于以编程方式在滚动视图中设置文本视图的文章。文本系统用户界面层编程指南:将 NSTextView 对象放入 NSScrollView你应该阅读它以获得最大的理解,但这里是代码:
NSScrollView *scrollview = [[NSScrollView alloc] initWithFrame:[[theWindow contentView] frame]];
NSSize contentSize = [scrollview contentSize];
[scrollview setBorderType:NSNoBorder];
[scrollview setHasVerticalScroller:YES];
[scrollview setHasHorizontalScroller:NO];
[scrollview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
theTextView = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, contentSize.width, contentSize.height)];
[theTextView setMinSize:NSMakeSize(0.0, contentSize.height)];
[theTextView setMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
[theTextView setVerticallyResizable:YES];
[theTextView setHorizontallyResizable:NO];
[theTextView setAutoresizingMask:NSViewWidthSizable];
[[theTextView textContainer] setContainerSize:NSMakeSize(contentSize.width, FLT_MAX)];
[[theTextView textContainer] setWidthTracksTextView:YES];
[scrollview setDocumentView:theTextView];
[theWindow setContentView:scrollview];
[theWindow makeKeyAndOrderFront:nil];
[theWindow makeFirstResponder:theTextView];
textStorage
然后,您可以通过对其对象进行操作来设置文本视图的文本:
theTextView.textStorage.attributedString = attributedString;