实现一个UILabel中的字体是不同样式

文章目录

    • 前言
    • NSMutableAttributedString
      • 字符串属性

前言

在仿写share时遇到这个问题
实现一个UILabel中的字体是不同样式_第1张图片
这个标题很明显是一个Label,但是在一个Label中字体却是不同大小,所以去搜来一下,发现需要用到可变的属性字符串NSMutableAttributedString,所以在这里做一下记录。

NSMutableAttributedString

//创建一个可变的属性字符串
    NSMutableAttributedString *mutableStr = [[NSMutableAttributedString alloc]initWithString:@"关于设计反馈的5件事  share小白"];
    /**给字符串中
     *NSMakeRange( x, number)范围内的字符
     *加属性addAttribute
     *value:属性的具体值
     */
    [mutableStr addAttribute:NSFontAttributeName value:[UIFont italicSystemFontOfSize:40] range:NSMakeRange(0, 10)];
    [mutableStr addAttribute:NSFontAttributeName value:[UIFont italicSystemFontOfSize:20] range:NSMakeRange(11, 7)];
    //创建Label
    UILabel *label = [[UILabel alloc]init];
    label.frame = CGRectMake(20, 100, 300, 80);
    label.numberOfLines = 0;
    //将当前样式文本设为可变的属性字符串
    label.attributedText = mutableStr;
    [self.view addSubview:label];

效果如下:
实现一个UILabel中的字体是不同样式_第2张图片
具体数值根据要求更改。

字符串属性

字符串属性有很多,我觉得常用的就这几个:

  • NSFontAttributeName 设置字体大小
    • 属性的具体值[UIFont italicSystemFontOfSize:40]
  • NSForegroundColorAttributeName 设置字体颜色
  • NSUnderlineStyleAttributeName 设置下划线风格
    • 属性的具体值:
      @(NSUnderlineStyleThick)
      @(NSUnderlineStyleDouble)
  • NSStrikethroughStyleAttributeName 删除线
    • 属性的具体值:和下划线类似

若想了解更多字符串属性,可以看看这2篇博客

NSAttributedString 属性整理
NSAttributedString使用方法整理

你可能感兴趣的:(学习笔记)