Search code examples
cocoanstextviewnsscrollview

Auto-Resizing of NSTextView and/or NSScrollView


I have an NSTextView inside an NSView (which is being used by a NSPopover, don't know if that is relevant) that I'm trying to resize automatically and programmatically (cf caption).

enter image description here

I have been struggling with a lot of stuff, namely :

  • Looking at NSLayoutManager and usedRectForTextContainer that give me aberrant size values (usedRectForTextContainer : {{0, 0}, {0.001, 28}})
  • Modifying NSScrollView frame, [NSScrollView contentView], [NSScrollView documentView]
  • Getting rid of AutoLayout

I reached the point where I can resize my scollview and my Popover, but I can't get the actual height of the text inside the NSTextView.

Any kind of help would be appreciated.

-(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 ?

}

Solution

  • I still have no idea why I can't use [layout usedRectForTextContainer:container], but I managed to get the NSTextView's height by using :

    -(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;
    }