NSTextView 和/或 NSScrollView 的自动调整大小

Ber*_*ron 5 cocoa nstextview nsscrollview

我有一个NSTextView内部 an NSView(正在被 a 使用NSPopover,不知道这是否相关),我正在尝试以编程方式自动调整大小(参见标题)。

在此处输入图片说明

我一直在努力解决很多问题,即:

  • 看着NSLayoutManagerusedRectForTextContainer,让我异常的大小值(usedRectForTextContainer : {{0, 0}, {0.001, 28}}
  • 修改NSScrollView frame, [NSScrollView contentView],[NSScrollView documentView]
  • 摆脱自动布局

我达到了可以调整 scollview 和 Popover 大小的程度,但是我无法获得 NSTextView 中文本的实际高度。

任何形式的帮助将不胜感激。

-(void)resize
{
    //Get clipView and scrollView
    NSClipView* clip = [popoverTextView superview];
    NSScrollView* scroll = [clip superview];

    //First, have an extra long contentSize and ScrollView to test everything else
    [popover setContentSize:NSMakeSize([popover contentSize].width, 200)];
    [scroll setFrame:(NSRect){
        [scroll frame].origin.x,[scroll frame].origin.y,
        [scroll frame].size.width,155
    }];



    NSLayoutManager* layout = [popoverTextView layoutManager];
    NSTextContainer* container = [popoverTextView textContainer];

    NSRect myRect = [layout usedRectForTextContainer:container]; //Broken
    //Now what ?

}
Run Code Online (Sandbox Code Playgroud)

Ber*_*ron 4

我仍然不知道为什么我不能使用,但我设法通过使用[layout usedRectForTextContainer:container]获得了高度:NSTextView

-(void)resize
{
    //Get glyph range for boundingRectForGlyphRange:
    NSRange range = [[myTextView layoutManager] glyphRangeForTextContainer:container];

    //Finally get the height
    float textViewHeight = [[myTextView layoutManager] boundingRectForGlyphRange:range
                                       inTextContainer:container].size.height;
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用“usedRectForTextContainer:”,它没有损坏。问题是它不布局文本,因此您需要首先调用 `glyphRangeForTextContainer:` 来布局文本。 (4认同)