gpt4 book ai didi

ios - 未返回 attributedText 的高度

转载 作者:行者123 更新时间:2023-11-29 00:13:43 24 4
gpt4 key购买 nike

我需要在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;
}

enter image description here

对于宽度 343,高度为 915,这是不准确的。

最佳答案

您可以使用boundingRectWithSize

 NSAttributedString *attrStr = [[NSAttributedString alloc]initWithString:@"<p>The HTML <strong>&lt;strong&gt;</strong> element defines <strong>strong</strong>text, with added semantic importance.</p>"];

// your attributed string
CGFloat width = 200; // whatever your desired width is
CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];;

NSLog(@"%@",NSStringFromCGRect(rect));

关于ios - 未返回 attributedText 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45773132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com