Last active
August 29, 2015 13:57
-
-
Save westerlund/9529125 to your computer and use it in GitHub Desktop.
Calculate NSString height with multiple attributes
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
// | |
// 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 |
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
// | |
// 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