创建 NSTextView

图形

在 XCode 中,可以通过从对象库中拖放一个简单的 NSTextView 来创建它。

StackOverflow 文档

此 NSTextView 位于 NSScrollView 内,该 NSScrollView 自动设置为使用文本视图垂直扩展。确保选项(⌥) - 拖拽时连接到文本视图而不是滚动视图。

StackOverflow 文档

编程

以编程方式创建 NSTextView 允许更好的控制和自定义。它稍微困难一些,需要对文本系统的了解才能充分发挥它的潜力。有关文本系统的更多信息,请点击此处 。以编程方式进行文本视图所需的基础知识如下:

  • 完全正常运行的 NSTextView 需要三个其他对象才能工作:

    1. NSLayoutManager - 执行字形/字符布局。
    2. NSTextContainer - 控制字形/字符可以驻留的图形空间。
    3. NSTextStorage - 保存 NSTextView 显示的实际字符串数据。
  • NSTextStorage 可以有许多 NSLayoutManager,但 NSLayoutManager 只能有一个 NSTextStorage。如果你希望以不同方式同时显示相同的数据,这将非常有用。

  • NSLayoutManager 可以有很多 NSTextContainer。对分页文本很有用。

  • NSTextView 一次只能有一个 NSTextContainer。

  • 在撰写本文时,NSTextView 中内置的某些内容是不受限制的。例如,内置的查找和替换功能无法自定义,但可以使用自定义功能覆盖。

有关如何使用文本系统的更多信息,请参见此处

现在为代码。这段代码将创建一个简单的 NSTextView,甚至不滚动。滚动和分页等内容将在另一个例子中。

Objective-C

// This code resides in an NSDocument object's windowControllerDidLoadNib:(NSWindowController *)windowController method.
// This is done simply because it is easy and automatically gets called upon.

// This method is also where the following NSRect variable gets size information. We need this information for this example.
NSRect windowFrame = windowController.window.contentView.frame;
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:@"Example text!"];
NSLayoutManager *manager = [[NSLayoutManager alloc] init];
NSTextContainer *container = [[NSTextContainer alloc] initWithContainerSize:NSMakeSize(windowFrame.size.width, windowFrame.size.height)];
NSTextView *textView = [[NSTextView alloc] initWithFrame:windowFrame textContainer:container];

[textStorage addLayoutManager:manager];
[manager addTextContainer:container];
[windowController.window setContentView:textView];

恭喜! 你已通过编程方式创建了 NSTextView!

StackOverflow 文档