美文网首页
iOS 富文本添加图片

iOS 富文本添加图片

作者: 隔墙送来秋千影 | 来源:发表于2018-07-17 11:22 被阅读314次
   //1.设置标签
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    titleLabel.backgroundColor = [UIColor yellowColor];
    titleLabel.text = @"石虎祝所有人步步高升,成为技术大神";
    titleLabel.textColor = [UIColor redColor];
    [self.view addSubview:titleLabel];


    //2.初始化富文本对象
     NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:titleLabel.text];

    //2.1修改富文本中的不同文字的样式
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 5)];//字体颜色    
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor purpleColor] range:NSMakeRange(7, 6)];//字体颜色   
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:22] range:NSMakeRange(0, 6)];//字体大小


    //3.初始化NSTextAttachment对象
    NSTextAttachment *attchment = [[NSTextAttachment alloc]init];
    attchment.bounds = CGRectMake(0, 0, 40, 40);//设置frame
    attchment.image = [UIImage imageNamed:@"release_homework"];//设置图片


    //4.创建带有图片的富文本
    NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:(NSTextAttachment *)(attchment)];
    [attributedString insertAttributedString:string atIndex:0];//插入到第几个下标
    [attributedString appendAttributedString:string];   //添加到尾部


    //5.用label的attributedText属性来使用富文本
    titleLabel.attributedText = attributedString;

相关文章

网友评论

      本文标题:iOS 富文本添加图片

      本文链接:https://www.haomeiwen.com/subject/vcywpftx.html