利用分類,NSString,增加一個方法。#import #import @interface NSString (Height)+ (CGSize)getRect:(NSString *)textStr andWidth:(CGSize)size andFont:(UIFont *)font;@e...
利用分類,NSString,增加一個方法。
#import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface NSString (Height) + (CGSize)getRect:(NSString *)textStr andWidth:(CGSize)size andFont:(UIFont *)font; @end
#import "NSString+Height.h" @implementation NSString (Height) + (CGSize)getRect:(NSString *)textStr andWidth:(CGSize)size andFont:(UIFont *)font { CGRect rect = [textStr boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil]; return rect.size; } @end
使用:
CGSize size = [NSString getRect:str andWidth:CGSizeMake(IOS_SCREEN.size.width/2 - 10, CGFLOAT_MAX) andFont:[UIFont systemFontOfSize:14]];