26
2017
09

ios开发中计算字符串的高度

//第一种算法,ios7.0后已经废弃

CGSize titleSize = [aString sizeWithFont:font constrainedToSize:CGSizeMake(@"label的宽度", MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];

//第二种算法ios7.0 后计算字符串的高度

CGRect rect = [aString boundingRectWithSize:CGSizeMake(@"label的宽度", MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : font} context:nil];

 NSLog(@"Height:::%f",rect.size.height);

封装

//此处1000为高度 还可以换为:MAXFLOAT

-(void)ViewDidload{

CGSizestringSize=[self sizeWithFont:font maxSize:CGSizeMake(SCREEN_WIDTH-20, 1000)string:aString];

float  textH= stringSize.height;

NSLog(@"textH:::%f",textH);

}

-(CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize string:(NSString *)string{

NSDictionary *attrs = @{NSFontAttributeName:font};

return [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;

}
上一篇:RecyclerView系列(7)—自定义LayoutManager 下一篇:渐变圆环进度条实现