NSAttributedString的妙用

一.给文字上面加删除线

UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(20, 50, 200, 50)]; 
[self.view addSubview:label]; label.text = @"10.00"; 
label.textAlignment = NSTextAlignmentCenter; 
label.textColor = [UIColor redColor]; 
// 横线的颜色跟随label字体颜色改变 
NSMutableAttributedString *newPrice = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"¥%@",label.text]]; 
[newPrice addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, newPrice.length)]; 
label.attributedText = newPrice;

效果:


给文字上面加删除线

二.UILabel实现图文混排

    NSMutableAttributedString *attri =  [[NSMutableAttributedString alloc] initWithString:@"连接前请先按Fn+F4切换到蓝牙连接手机/平板"];
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
    // 表情图片
    attch.image = [UIImage imageNamed:@"pop_pic_tip.png"];
     //设置图片大小
    attch.bounds = CGRectMake(0, 0, 17*(64/21.0),17);
    // 创建带有图片的富文本
    NSAttributedString *imgString = [NSAttributedString attributedStringWithAttachment:attch];
    [attri appendAttributedString:imgString];
    
    NSAttributedString *string = [[NSAttributedString alloc]initWithString:@"闪烁进入待连接状态" attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]}];
    [attri appendAttributedString:string];
    
    self.label01 = [[UILabel alloc]init];
    [self.contentView addSubview:self.label01];
    self.label01.numberOfLines = 0;
    [self.label01 setTextColor:[UIColor colorWithRGB:0x2f3641]];
    self.label01.attributedText = attri;
    [self.label01 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView.mas_left).mas_offset(16);
        make.right.mas_equalTo(self.contentView.mas_right).mas_offset(-16);
        make.top.mas_equalTo(self.imgView.mas_bottom).mas_offset(15);
    }];

效果:


UILabel的图文混排
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • iOS开发高级进阶(17-19)-数据存储 简易数据存储 数据持久化的方法: NSData 常在网络访问中使用 N...
    逸飞u阅读 6,375评论 0 8
  • 1能付出爱是一种能力,能收获他人的爱是一种幸福。 人是社会性的动物,马克思也说过“人是所有社会关系的总和”。积极入...
    一匹马来了阅读 3,935评论 0 0
  • 让我说说我身边的那个她吧!她会买手机比我的贵比我的好,但她却不知道手机的功能,微信qq微博她不懂,打字也只会笔画,...
    南街霸王餐阅读 1,716评论 0 0