Label是比較常用的一個(gè)控件,記錄一些比較使用的技術(shù)
一利朵、計(jì)算Label的高度
- 計(jì)算單行指定字體大小下的高度
-(CGSize)sizeWithAttributes:(nullable NSDictionary<NSString *, id> *)attrs NS_AVAILABLE(10_0, 7_0);
- 具體使用方法 例子:
NSString *testStr = @"Hello Word";
[testStr sizeWithAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14.0]}];//14.0為字體大小,根據(jù)實(shí)際情況而定
返回單行testStr的長(zhǎng)度和高度
- 指定寬度或者高度獲取文字的寬度或者高度
/**
* size: 文字顯示區(qū)域
* options
* attributes
* context
*/
/**
* NSStringDrawingUsesLineFragmentOrigin
* NSStringDrawingUsesFontLeading
* NSStringDrawingUsesDeviceMetrics
* NSStringDrawingTruncatesLastVisibleLine
*/
-(CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSString *, id> *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);
- 具體使用方法 例子:
CGSize totleSize = [titleboundingRectWithSize:CGSizeMake(YYTScreenW-28,MAXFLOAT)options:NSStringDrawingUsesLineFragmentOriginattributes:@{NSFontAttributeName: [UIFontsystemFontOfSize:14.0]}context:nil].size;
返回指定寬度下,文本的高度.同樣可以返回指定高度下,文本的寬度
- 計(jì)算文本行數(shù)
文本的總共高度 / 單行高度 = 文本行數(shù) - 具體使用方法 例子:
int numberLine =ceil(totleSize.height/ size.height);
備注:
- ceil:如果參數(shù)是小數(shù),則求最小的整數(shù)但不小于本身 例: ceil(3.141) = 4;
- round:如果參數(shù)是小數(shù),則求值為四舍五入 例: round(3.14) = 3; round(3.16) = 4;
- floor: 如果參數(shù)是小數(shù),則求最大的整數(shù)但不大于本身 例: ceil(3.141) = 3;
二酿箭、同一個(gè)Label中文字的大小或者顏色不同
- 需求:同一個(gè)Label需要展示不同顏色
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:@" 溫馨提示:請(qǐng)仔細(xì)核對(duì)繳費(fèi)信息"];
NSRange range = {0, 8};
NSRange rang1 = {8, 9};
UIColor *color = [UIColor colorWithRed:250 / 255.0 green:114 / 255.0 blue:59 / 255.0 alpha:1];
[attStr setAttributes:@{NSForegroundColorAttributeName : color} range:range];
[attStr setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:102 / 255.0 green:102 / 255.0 blue:102 / 255.0 alpha:1]} range:rang1];
label.attributedText = attStr;
后續(xù)繼續(xù)補(bǔ)充關(guān)于Label的知識(shí)點(diǎn)