【问题标题】:Height of attributedText not returned未返回属性文本的高度
【发布时间】: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 内容,并且存在换行符“&nbsp”。

+(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


【解决方案1】:

你可以使用 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));

【讨论】:

  • 如何指定内容换行必须是 wordWrapping 的类型?
  • 通过使用 NSMutableAttributedString 而不是 NSAttributedString 并添加此 NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping]; [attrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0,[attrStr length])];
猜你喜欢
  • 2018-02-15
  • 1970-01-01
  • 2014-09-21
  • 2013-08-02
  • 2014-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-17
相关资源
最近更新 更多