Skip to content

Instantly share code, notes, and snippets.

@westerlund
Last active August 29, 2015 13:57
Show Gist options
  • Save westerlund/9529125 to your computer and use it in GitHub Desktop.
Save westerlund/9529125 to your computer and use it in GitHub Desktop.
Calculate NSString height with multiple attributes
//
// NSAttributedString+sizeInWidth.h
//
// Created by Simon Westerlund on 13/03/14.
// Copyright (c) 2014 Simon Westerlund. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSAttributedString (sizeInWidth)
/*!
Returns the correct size for the attributed string
*/
- (CGSize)sizeInWidth:(CGFloat)width;
@end
//
// NSAttributedString+sizeInWidth.m
//
// Created by Simon Westerlund on 13/03/14.
// Copyright (c) 2014 Simon Westerlund. All rights reserved.
//
#import "NSAttributedString+sizeInWidth.h"
@implementation NSAttributedString (sizeInWidth)
- (CGSize)sizeInWidth:(CGFloat)width {
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:self];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(width, FLT_MAX)];
NSLayoutManager *layoutManager = [NSLayoutManager new];
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
[textStorage beginEditing];
[self enumerateAttributesInRange:NSMakeRange(0, [self length])
options:0
usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
[textStorage addAttributes:attrs range:range];
}];
[textStorage endEditing];
return [layoutManager usedRectForTextContainer:textContainer].size;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment