固定字符串宽度,计算字符串的高度
- 首先我是创建了NSString的类别NSString+NSStringTools,在类中先声明宏定义
///判断字符串是否为空或者为空字符串
#define StringIsNullOrEmpty111(str) (str == nil || [str isEqualToString:@""])
--------------------------------------------------
/**
* 获取文本的显示高度,
*/
+(CGRect)heightForString:(NSString *)str Size:(CGSize)size Font:(UIFont *)font;
+(CGRect)heightForString:(NSString *)str Size:(CGSize)size Font:(UIFont *)font Lines:(NSInteger)lines;
+ (CGRect)heightForString:(NSString *)str Size:(CGSize)size Font:(UIFont *)font
{
return [NSString heightForString:str Size:size Font:font Lines:0];
}
+ (CGRect)heightForString:(NSString *)str Size:(CGSize)size Font:(UIFont *)font Lines:(NSInteger)lines
{
if (StringIsNullOrEmpty111(str))
{
return CGRectMake(0, 0, 0, 0);
}
static UILabel *lbtext;
if (lbtext == nil)
{
lbtext = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
}
else
{
lbtext.frame = CGRectMake(0, 0, size.width, size.height);
}
lbtext.font = font;
lbtext.text = str;
lbtext.numberOfLines = lines;
CGRect rect = [lbtext textRectForBounds:lbtext.frame limitedToNumberOfLines:lines];
if(rect.size.height < 0)
{
rect.size.height = 0;
}
if (rect.size.width < 0)
{
rect.size.width = 0;
}
return rect;
}
//根据字符串的高度/一行的高度 = 展示的行数
-(int)numberRowsString:(NSString *)str size:(CGSize)size font:(UIFont *)font {
CGFloat height1 = [NSString heightForString:str Size:size Font:font].size.height;
//得到一行的字体高度
CGFloat height2 = [NSString heightForString:@"测试文字" Size:size Font:font].size.height;
return height1/height2;
}
NSString *tempStr = @"关关雎鸠,在河之洲。窈窕淑女,君子好逑。参差荇菜,左右流之。窈窕淑女,寤寐求之。求之不得,寤寐思服。悠哉悠哉,辗转反侧。参差荇菜,左右采之。窈窕淑女,琴瑟友之。参差荇菜,左右芼之。窈窕淑女,钟鼓乐之。";
int number = [self numberRowsString: tempStr size:200 , 100000) font:[UIFont systemFontOfSize:11]];
NSLog(@"行数 == %d",number);
- 输出出来的结果就是这个字符串在宽度为200的情况下的能展示多少行了