Bertrand Caron
Bertrand Caron

Reputation: 2657

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 :

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 ?

}

Upvotes: 5

Views: 3884

Answers (2)

jiminybob99
jiminybob99

Reputation: 873

Here is some functional code that I have tested myself for swift. usedRectForTextContainer is not broken it just is set lazily. To set it i call glyphrangefortextcontainer

I found the answer here: http://stpeterandpaul.ca/tiger/documentation/Cocoa/Conceptual/TextLayout/Tasks/StringHeight.html

    let textStorage = NSTextStorage(string: newValue as! String)
    let textContainer = NSTextContainer(size: NSSize(width: view!.Text.frame.width, height:CGFloat.max))
    let layoutManager = NSLayoutManager()

    layoutManager.addTextContainer(textContainer)
    textStorage.addLayoutManager(layoutManager)

    textContainer.lineFragmentPadding = 0.0
    textContainer.lineBreakMode = NSLineBreakMode.ByWordWrapping
    textStorage.font = NSFont(name: "Times-Roman", size: 12)

    layoutManager.glyphRangeForTextContainer(textContainer)

    let rect = layoutManager.usedRectForTextContainer(textContainer)

    Swift.print(rect)

The documentation also suggest that is the the case:

pic of documentation

Upvotes: 3

Bertrand Caron
Bertrand Caron

Reputation: 2657

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

Upvotes: 4

Related Questions