Last active
December 17, 2015 16:49
-
-
Save Kr1sso/5641584 to your computer and use it in GitHub Desktop.
Cocoa Text Height Calculation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Initialize to your properties | |
self.wlNoteEditor = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, 1, 1)]; | |
[self.wlNoteEditor setAutoresizingMask:NSViewWidthSizable]; | |
[[self.wlNoteEditor textContainer] setContainerSize:NSMakeSize(self.wlNoteEditorContainer.contentSize.width, FLT_MAX)]; | |
[[self.wlNoteEditor textContainer] setWidthTracksTextView:YES]; | |
CGFloat spacing = 7.0f; | |
NSMutableParagraphStyle *para = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; | |
[para setLineSpacing:spacing]; | |
[para setMaximumLineHeight:16]; | |
[para setMinimumLineHeight:16]; | |
[self.wlNoteEditor setDefaultParagraphStyle:para]; | |
// Make the linespaceing work, by setting a random placeholder, this is a bug in NSTextView | |
[self.wlNoteEditor setString:@"placeholder"]; | |
[self.wlNoteEditor setTextContainerInset:NSMakeSize(17, 7)]; | |
[self.wlNoteEditor setFont:[NSFont fontWithName:@"HelveticaNeue" size:13.0]]; | |
. | |
. | |
[[self.wlNoteEditor textStorage] setAttributedString:someAtrString]; | |
. | |
. | |
[self.wlNoteEditor.layoutManager glyphRangeForTextContainer:self.wlNoteEditor.textContainer]; | |
CGFloat height = [self.wlNoteEditor.layoutManager usedRectForTextContainer:self.wlNoteEditor.textContainer].size.height; | |
Height is a 100 % perfect match now, adjust font etc, the text view is used with a dispatch_once to keep it off screen for continuous height calculation. Hope it helps! : |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment