<span style="font-family: Menlo; background-color: rgb(255, 255, 255);">这段代码应该是大多数人工具类中都有的, 但是真要用的时候一时又想不起来, 需要去找, 在这儿写出来方便以后用</span>
</pre><pre name="code" class="objc">//计算字符串长度
+ (CGSize)sizeWithText:(NSString *)text font:(CGFloat)font
{
CGSize size = [text sizeWithAttributes:@{NSFontAttributeName:
[UIFont systemFontOfSize:ResultSize(font)],
NSStrokeColorAttributeName:
[UIColor blackColor],
NSForegroundColorAttributeName:
[UIColor blackColor]}];
return size;
}
今天又遇到个计算高度问题, 是NSAttributedString 之后在动态计算高度, 但是会发现用上边的方法因为文字间距变大, 所以算出来的距离不准,便把间距也加进去
+ (CGSize)sizeOfTextFontSize:(CGFloat)fontSize maxSize:(CGSize)maxSize spacing:(CGFloat)spacing
{
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:spacing];
NSDictionary *attrs = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSParagraphStyleAttributeName: paragraphStyle};
return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}