zoukankan      html  css  js  c++  java
  • 【iOS】UILabel多行文本的高度计算

    平时这些代码用的时候,总是要搜索查阅,自己索性整理下记一笔,节约生命。

    实现是直接给NSString类添加一个分类,并添加了计算文本高度的两个方法:

    声明代码:

     1 #import <Foundation/Foundation.h>
     2 
     3 @interface NSString (Size)
     4 
     5 /**
     6  * 计算单行文本的高度
     7  */
     8 - (CGFloat)heightWithLabelFont:(UIFont *)font;
     9 /**
    10  * 计算多行文本的高度
    11  */
    12 - (CGFloat)heightWithLabelFont:(UIFont *)font withLabelWidth:(CGFloat)width;
    13 @end

    具体的实现代码:

     1 #import "NSString+Size.h"
     2 
     3 @implementation NSString (Size)
     4 
     5 - (CGFloat)heightWithLabelFont:(UIFont *)font withLabelWidth:(CGFloat)width {
     6     CGFloat height = 0;
     7     
     8     if (self.length == 0) {
     9         height = 0;
    10     } else {
    11         NSDictionary *attribute = @{NSFontAttributeName:font};
    12         CGSize rectSize = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
    13                                             options:NSStringDrawingTruncatesLastVisibleLine|
    14                                                     NSStringDrawingUsesLineFragmentOrigin|
    15                                                     NSStringDrawingUsesFontLeading
    16                                          attributes:attribute
    17                                             context:nil].size;
    18         height = rectSize.height;
    19     }
    20     return height;
    21 }
    22 
    23 - (CGFloat)heightWithLabelFont:(UIFont *)font {
    24     CGFloat height = 0;
    25     if (self.length == 0) {
    26         height = 0;
    27     }else{
    28         CGSize rectSize = [self sizeWithAttributes:@{NSFontAttributeName:font}];
    29         height = rectSize.height;
    30     }
    31     return height;
    32 }
    33 
    34 @end
  • 相关阅读:
    #3146. 「APIO 2019」路灯
    #3145. 「APIO 2019」桥梁
    #3144. 「APIO 2019」奇怪装置
    雅礼集训2019 D7T2 Subsequence
    Luogu P3600 随机数生成器
    CF 704 D. Captain America
    Luogu P2570 [ZJOI2010]贪吃的老鼠
    Loj #2585. 「APIO2018」新家
    Access denied for user 'root'@'localhost' (using password: NO)
    MySql修改密码
  • 原文地址:https://www.cnblogs.com/vokie/p/5356096.html
Copyright © 2011-2022 走看看