Skip to content

Instantly share code, notes, and snippets.

@luowei
Created November 21, 2016 03:53
Show Gist options
  • Save luowei/31d0c2185050a9e025edbc0aefc727dd to your computer and use it in GitHub Desktop.
Save luowei/31d0c2185050a9e025edbc0aefc727dd to your computer and use it in GitHub Desktop.
NSString OC扩展
@interface NSString (Ext)
- (CGFloat)widthWithFont:(UIFont *)font andAttributes:(NSDictionary *)attributes;
- (CGFloat)heigthWithWidth:(CGFloat)width andFont:(UIFont *)font andAttributes:(NSDictionary *)attributes;
- (void)enumerateCharactersUsingBlock:(void (^)(NSString *character, NSInteger idx, bool *stop))block;
@end
//------- Implementation -------
@implementation NSString (Ext)
- (CGFloat)widthWithFont:(UIFont *)font andAttributes:(NSDictionary *)attributes {
return [[[NSAttributedString alloc] initWithString:self attributes:attributes] size].width;
}
- (CGFloat)heigthWithWidth:(CGFloat)width andFont:(UIFont *)font andAttributes:(NSDictionary *)attributes {
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:self attributes:attributes];
CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
return rect.size.height;
}
- (void)enumerateCharactersUsingBlock:(void (^)(NSString *character, NSInteger idx, bool *stop))block {
bool _stop = NO;
for (NSInteger i = 0; i < [self length] && !_stop; i++) {
NSString *character = [self substringWithRange:NSMakeRange(i, 1)];
block(character, i, &_stop);
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment