MacOS 开发 - NSTextView

版权声明:本文为博主原创文章,转载请附上本文链接地址。from : https://blog.csdn.net/lovechris00 https://blog.csdn.net/lovechris00/article/details/78014081


NSTextView 有趣的地方很多,这里慢慢贴


常见用法:

作为 NSScrollView 的 DocumentView


    NSScrollView *scrolleView = [[NSScrollView alloc]init];
    self.scrollView = scrolleView;
    [bgView addSubview:scrolleView];
   
//    scrolleView.contentInsets = NSEdgeInsetsMake(12, 20, 12, 20); //无效
    
    [scrolleView setHasVerticalScroller:NO];
    [scrolleView setHasHorizontalScroller:YES];  //滚动条
    
    NSTextView *txView = [[NSTextView alloc]init];
    [txView setAutoresizingMask:NSViewHeightSizable];
    txView.frame = NSMakeRect(0, 0,contentSize.width, contentSize.height);
    [txView setMinSize:contentSize];
    [txView setMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
   
    [txView setAutoresizingMask:NSViewWidthSizable];
    
    [[txView textContainer] setContainerSize:NSMakeSize(contentSize.width - 40, FLT_MAX)];
    [[txView textContainer] setWidthTracksTextView:YES];
    
    [txView setVerticallyResizable:YES];
    [txView setHorizontallyResizable:YES];
    
    txView.editable = NO;  //只显示
    
    [scrolleView setDocumentView:txView];

常用属性


设置颜色

无效

    [scrolleView msSetLayerColor:[NSColor redColor]];
    [txView msSetLayerColor:[NSColor yellowColor]];

有效

   scrolleView.backgroundColor = [NSColor redColor];
    txView.backgroundColor = [NSColor yellowColor];

使用 NSAttributedString

错误、崩溃

self.textView.attributedString = [[NSAttributedString alloc]initWithString:detailStr attributes:attributes];

正确

NSAttributedString *str = [[NSAttributedString alloc]initWithString:detailStr attributes:attributes];
 [self.textView.textStorage appendAttributedString:str];


NSTextView & NSTextField 比较

  • 从表面上看,前者比后者功能丰富,前者一般用作复杂的文字编辑,后者一般接受简单的数据输入。
  • 二者处理 Enter 和 Tab 键的行为不同。NSTextView 的方式和通常的编辑器相同:给编辑内容添加换行或者 tab 字符。
  • NSTextField 的方式则类似于其它非文本编辑的Cocoa 控件:Enter 键触发 target action(缺省为终止编辑),Tab 键令焦点移到相邻的下一控件。

当一个 NSTextField 控件不拥有焦点的时候,它只显示自己存储的文本值,并不和 NSTextView 有任何关系。

当它获得焦点时,其所在的窗口会把一个 NSTextView 控件置于其上,并将原来的 NSTextField 对象设置为该 NSTextView 对象的 delegate。

所以,真正获取焦点并且成为 first responder 的控件是 NSTextView 对象。在同一窗口中,置于所有 NSTextField 之上的,是同一个 NSTextView 对象实例。因为只有一个控件能获得焦点,所以共享单一的 NSTextView 实例没有问题。这个唯一的实例称为「field editor」,即放置在 text field 上的 editor。Field editor 由窗口负责创建和管理。


参考资料:

Sodas lay:NSTextField与NSTextView
http://blog.csdn.net/sodaslay/article/details/8313126


猜你喜欢

转载自blog.csdn.net/lovechris00/article/details/78014081