美文网首页
iOS - UITextView计算行数的和字符串行高

iOS - UITextView计算行数的和字符串行高

作者: HanZhiZzzzz | 来源:发表于2022-02-22 14:34 被阅读0次
    - (CGFloat )returnTextHeightWithStr:(NSString *)str withFont:(UIFont *)font WithWidth:(CGFloat)width WithLineSpacing:(CGFloat)lineSpacing  {
        UITextView* _textView = [[UITextView alloc]init];
        _textView.font = font;
        //设置行间距
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
        paragraphStyle.lineSpacing = lineSpacing;
        NSMutableAttributedString *titleAttr = [[NSMutableAttributedString alloc] initWithString:str];
        [titleAttr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, titleAttr.length)];
        [titleAttr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, titleAttr.length)];
        _textView.attributedText = titleAttr;
        CGSize maxSize = CGSizeMake(width,CGFLOAT_MAX);
        CGSize newSize = [_textView sizeThatFits:maxSize];
        CGFloat height = ceilf(newSize.height);
        return height;
    }
    
    extension String {
        
        //获取内容size
        func getContentSize(font: UIFont, size: CGSize) -> CGSize {
            if self.count == 0 {
                return CGSize.zero
            }
            return (self as NSString).boundingRect(with: size, options: NSStringDrawingOptions(rawValue: NSStringDrawingOptions.usesLineFragmentOrigin.rawValue | NSStringDrawingOptions.usesFontLeading.rawValue), attributes: [.font: font], context: nil).size
        }
        func getContentHeight(font: UIFont, width: CGFloat) -> CGFloat {
            return self.getContentSize(font: font, size: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)).height
        }
        func getContentWidth(font: UIFont, height: CGFloat) -> CGFloat {
            return self.getContentSize(font: font, size: CGSize(width: CGFloat.greatestFiniteMagnitude, height: height)).width
        }
    }
    

    相关文章

      网友评论

          本文标题:iOS - UITextView计算行数的和字符串行高

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