Skip to content

Instantly share code, notes, and snippets.

@chrene
Created August 5, 2013 18:01
Show Gist options
  • Save chrene/6158025 to your computer and use it in GitHub Desktop.
Save chrene/6158025 to your computer and use it in GitHub Desktop.
NSString extension that allows calculating the size of a string more like sizeWithFont:
//
// NSString+sizeWithFont.h
// UTNoteLabelView
//
// Created by Christian Enevoldsen on 05/08/13.
// Copyright (c) 2013 Utunity. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSString (sizeWithFont)
- (CGSize)sizeOfStringWithFont:(UIFont*)font;
- (CGSize)sizeOfStringWithFont:(UIFont*)font constrainedToSize:(CGSize)size;
- (CGSize)sizeOfStringWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode;
@end
//
// NSString+sizeWithFont.m
// UTNoteLabelView
//
// Created by Christian Enevoldsen on 05/08/13.
// Copyright (c) 2013 Utunity. All rights reserved.
//
#import "NSString+sizeWithFont.h"
@implementation NSString (sizeWithFont)
- (CGSize)sizeOfStringWithFont:(UIFont *)font {
return [self sizeOfStringWithFont:font constrainedToSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX)];
}
- (CGSize)sizeOfStringWithFont:(UIFont *)font constrainedToSize:(CGSize)size {
return [self sizeOfStringWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
}
- (CGSize)sizeOfStringWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode {
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:self];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:size];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
[textStorage addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, self.length)];
[textContainer setLineBreakMode:lineBreakMode];
[textContainer setLineFragmentPadding:0.0];
(void)[layoutManager glyphRangeForTextContainer:textContainer];
return [layoutManager usedRectForTextContainer:textContainer].size;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment