iOS 手記 - 計算文字高度/寬度:- (CGSize)sizeWithAttributes:(NSDictionary *)attrs

  

計算NSString 的 size:函數

- (CGSize)sizeWithAttributes:(NSDictionary<NSString *,id> *)attrs;spa

Parameters:

  類型:NSDictionary3d

  文字的屬性字典,例如 NSFontAttributeNamecode

  也可使用 NSAttributedString 的屬性字典,由於是 NSString 對象,因此設置的是整個 string 的屬性,而非 string的某一段 rangs。對象

Return Value:  

  類型:CGSizeblog

  返回設置了屬性的文字佔用的邊界框大小,即這段文字的寬度與高度。 string

 

注意:it

  返回的是帶小數的 size, 當使用這個 size 去設置 view 的 frame 時, 須要使用ceil() 函數來取 size 的 某個成員(width/height)的整數值。io

 

例:class

CGSize titleSize = [tagModel.title sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:8]}];

titleLabel.frame = CGRectMake(0, 0, ceil(titleSize.width), ceil(titleSize.height));
相關文章
相關標籤/搜索