【iOS】UILabel多行文本的高度計算

來源:互聯網
上載者:User

標籤:

平時這些代碼用的時候,總是要搜尋查閱,自己索性整理下記一筆,節約生命。

實現是直接給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                                                     NSStringDrawingUsesFontLeading16                                          attributes:attribute17                                             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

 

【iOS】UILabel多行文本的高度計算

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.