** 一.封装**
- (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize{
NSDictionary *attr = @{NSFontAttributeName : font};
return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attr context:nil].size;
}
例子:
CGSize textSize = [self sizeWithText:message.text font:MNTextFont maxSize:CGSizeMake(200, MAXFLOAT)];
if (message.type == MNMessageTypeOther) {
_textF = CGRectMake(CGRectGetMaxX(_iconF) + 10, CGRectGetMaxY(_timeF)+15, textSize.width+40, textSize.height+40);
}else{
_textF = CGRectMake(screenW-10-40-10-textSize.width-40, CGRectGetMaxY(_timeF)+15, textSize.width+40, textSize.height+40);
}
** 二.分类中封装**
1.创建分类文件 NSString+Extension.h/NSString+Extension.m
2.在NSString+Extension.h中创建方法
- (CGSize)sizeWithfont:(UIFont *)font maxSize:(CGSize)maxSize
3.在NSString+Extension.m中实现该方法
- (CGSize)sizeWithfont:(UIFont *)font maxSize:(CGSize)maxSize{
NSDictionary *attr = @{NSFontAttributeName : font};
return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attr context:nil].size;
}
例子:
CGSize textSize = [message.text sizeWithfont:MNTextFont maxSize:CGSizeMake(200, MAXFLOAT)];
if (message.type == MNMessageTypeOther) {
_textF = CGRectMake(CGRectGetMaxX(_iconF) + 10, CGRectGetMaxY(_timeF)+15, textSize.width+40, textSize.height+40);
}else{
_textF = CGRectMake(screenW-10-40-10-textSize.width-40, CGRectGetMaxY(_timeF)+15, textSize.width+40, textSize.height+40);
** 三.部分可能会出现自适应高度后文字无法显示完整**
把label的属性adjustsFontSizeToFitWidth设置成yes就好了
网友评论