Created
November 21, 2016 03:53
-
-
Save luowei/31d0c2185050a9e025edbc0aefc727dd to your computer and use it in GitHub Desktop.
NSString OC扩展
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
@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