对NSString添加一个分类
声明头文件类 .h文件:以下为几种方法
#import <Foundation/Foundation.h>
@interface NSString (size)
- (CGSize)sizeWithFont:(UIFont*)font andMaxSize:(CGSize)size;
+ (CGSize)sizeWithString:(NSString*)str andFont:(UIFont*)font andMaxSize:(CGSize)size;
+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxW:(CGFloat)maxW;
+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font;
@end
实现类 .m文件
#import "NSString+size.h"
@implementation NSString (size)
- (CGSize)sizeWithFont:(UIFont*)font andMaxSize:(CGSize)size
{
//特殊的格式要求都写在属性字典中
NSDictionary*attrs =@{NSFontAttributeName: font}; //返回一个矩形,大小等于文本绘制完占据的宽和高。
return [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}
+ (CGSize)sizeWithString:(NSString*)str andFont:(UIFont*)font andMaxSize:(CGSize)size
{
NSDictionary*attrs =@{NSFontAttributeName: font};
return [str boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}
+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxW:(CGFloat)maxW
{
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = font;
CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingUsesFontLeading attributes:attrs context:nil].size;
}
+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font
{
return [self sizeWithText:text font:font maxW:MAXFLOAT];
}
如有更好的方法,请留言交流
网友评论