iOS Label的一些总结

Label是比较常用的一个控件,记录一些比较使用的技术

一、计算Label的高度

  • 计算单行指定字体大小下的高度
-(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为字体大小,根据实际情况而定

返回单行testStr的长度和高度

  • 指定宽度或者高度获取文字的宽度或者高度
/**
 * size: 文字显示区域
 * 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;

返回指定宽度下,文本的高度.同样可以返回指定高度下,文本的宽度

  • 计算文本行数
    文本的总共高度 / 单行高度 = 文本行数
  • 具体使用方法 例子:
int numberLine =ceil(totleSize.height/ size.height);

备注:

  • ceil:如果参数是小数,则求最小的整数但不小于本身 例: ceil(3.141) = 4;
  • round:如果参数是小数,则求值为四舍五入 例: round(3.14) = 3; round(3.16) = 4;
  • floor: 如果参数是小数,则求最大的整数但不大于本身 例: ceil(3.141) = 3;

二、同一个Label中文字的大小或者颜色不同

  • 需求:同一个Label需要展示不同颜色
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:@"   温馨提示:请仔细核对缴费信息"];
    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;

后续继续补充关于Label的知识点

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容