iOS_计算文本高度

来源:互联网 发布:淘宝自助装机 编辑:程序博客网 时间:2024/05/16 00:42

<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;}



0 0
原创粉丝点击