码迷,mamicode.com
首页 > 移动开发 > 详细

iOS动态计算Label的宽高

时间:2015-09-11 20:44:00      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:

1.根据文字计算Label的宽度

技术分享
1 +(CGFloat)widthOfString:(NSString *)string font:(UIFont *)font height:(CGFloat)height
2 {
3     NSDictionary * dict=[NSDictionary dictionaryWithObject: font forKey:NSFontAttributeName];
4     CGRect rect=[string boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
5     return rect.size.width;
6 }
View Code

 

2.根据文字计算Label的高度

2.1方法一:sizeThatFits

例如:CGSize size = [toolLabel sizeThatFits:CGSizeMake([UIScreen mainScreen].bounds.size.width, MAXFLOAT)];

得到的size.height就是Label的高度

2.2方法二:

技术分享
+(CGFloat)heightOfString:(NSString *)string font:(UIFont *)font width:(CGFloat)width
{
    CGRect bounds;
    NSDictionary * parameterDict=[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    bounds=[string boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:parameterDict context:nil];
    return bounds.size.height;
}
View Code

 

iOS动态计算Label的宽高

标签:

原文地址:http://www.cnblogs.com/liaods/p/4801909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!