【发布时间】:2017-08-19 15:12:39
【问题描述】:
我需要在 UITableViewCell 中显示文字,需要设置 tableView 的高度。我正在使用以下方法动态计算行高。但是身高比实际身高要高很多。
+ (CGFloat)getquestionLabelHeight:(NSNumber *)width text:(NSString *)text {
CGSize constraint = CGSizeMake([width floatValue], CGFLOAT_MAX);
NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGSize boundingBox = [[ZUtility getAttributedText:text].string boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[UIFont fontWithName:@"OpenSans" size:14]} context:context].size;
return boundingBox.height;
}
我将文本转换为属性文本的原因是因为普通文本具有 html 内容,并且存在换行符“ ”。
+(NSAttributedString *)getAttributedText:(NSString *)text {
NSMutableAttributedString *attrHTMLText = [[[NSAttributedString alloc] initWithData:[text dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} documentAttributes:nil error:nil] mutableCopy];
[attrHTMLText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"OpenSans" size:14.0] range:NSMakeRange(0, attrHTMLText.length)];
[attrHTMLText addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, attrHTMLText.length)];
return attrHTMLText;
}
对于宽度 343,高度是 915,这是不准确的。
【问题讨论】:
-
为什么你不这样做有约束? @Astha Gupta
标签: ios objective-c uitableview nsstring nsattributedstring