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
  • 相关阅读:
    php 可变函数用法
    javascript语法里一些难点问题
    jquery技巧总结
    Bootstrap学习笔记
    Linux下中文文件名乱码问题的详解
    php中iconv函数使用方法,解决中文乱码
    web制作、开发人员需知的Web缓存知识
    鲍鱼开始讲八皇后了
    鲍鱼开始讲八皇后了
    double links....baoyuzuoye
  • 原文地址:https://www.cnblogs.com/vokie/p/5356096.html
Copyright © 2011-2022 走看看