美文网首页
iOS计算文字的高度

iOS计算文字的高度

作者: 不要虚度美好的时光 | 来源:发表于2021-09-24 21:04 被阅读0次

计算文字的高度:

#define kScreenWidth          [[UIScreen mainScreen] bounds].size.width
#define HomePage_Collection_Cell_Title_FrameWidth ((kScreenWidth - 25)/2.0 - 15 - 22)

- (double)calculateTitleHeight:(NSString*)strTitle {
    NSLog(@"calculateTitleHeight: %@", strTitle);
    // 计算出每个Cell的高度
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:strTitle];
    
    UIFont *font = [UIFont systemFontOfSize:17.0];
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    // TODO: 行间距可以设置成动态的
    style.lineSpacing = 2; // [self.lineSpaceTextField.text integerValue];
    
    [attributeString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, strTitle.length)];
    
    [attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, strTitle.length)];
    
//    self.showTextLabel.attributedText = attributeString;
//    
//    //        NSLog(@"textView.text.length:%lf", textView.text.length)
    
    
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    
    CGFloat boundingRectHeight = [attributeString boundingRectWithSize:CGSizeMake(HomePage_Collection_Cell_Title_FrameWidth, MAXFLOAT) options:options context:nil].size.height;
    if ([attributeString.string isEqualToString:@""] || [attributeString.string isEqualToString:@"(null)"]) {
        boundingRectHeight = 0;
    }
    NSLog(@"boundingRectHeight: %lf", boundingRectHeight);
    return boundingRectHeight;
}

相关文章

网友评论

      本文标题:iOS计算文字的高度

      本文链接:https://www.haomeiwen.com/subject/eyxtnltx.html