- (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
}
}
网友评论