美文网首页
IOS 计算字符串的宽高

IOS 计算字符串的宽高

作者: FMaarten | 来源:发表于2018-12-12 19:12 被阅读0次

对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];
}

如有更好的方法,请留言交流

相关文章

网友评论

      本文标题:IOS 计算字符串的宽高

      本文链接:https://www.haomeiwen.com/subject/geiphqtx.html