IOS-动态计算文本的宽度,来定义控件的frame大小。
//根据传过来的文字内容,文字大小,和最大尺寸动态计算文字所占用的size
- (CGSize)labelAutoCalculateRectWith:(NSString*)text FontSize:(CGFloat)fontSize MaxSize:(CGSize)maxSize
{
NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc]init];
paragraphStyle.lineBreakMode=NSLineBreakByWordWrapping;
NSDictionary* attributes =@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSParagraphStyleAttributeName:paragraphStyle.copy};
//如果系统为iOS7.0;
CGSize labelSize;
if (![text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]){
labelSize = [text sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
}
//如果是IOS6.0
else
{
labelSize = [text boundingRectWithSize: maxSize
options: NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine
attributes:attributes
context:nil].size;
}
labelSize.height=ceil(labelSize.height);
labelSize.width=ceil(labelSize.width);
return labelSize;
}
//调用的函数
CGSize maxSize = CGSizeMake(MAXFLOAT, 40);
CGSize titleSize = [self labelAutoCalculateRectWith:_publicDetail.name FontSize:15.0f MaxSize:maxSize];
UILabel *label = [UILabel alloc]init];
label.frame = CGRectMake(0 , 0, titleSize.width, titleSize.height);
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。