iOS 富文本添加图片

1、概念

  1. 添加图片效果图
  2. 富文本添加图片代码
  3. 富文本总结
  4. 直接拷贝代码就能够用

2、添加图片效果图

这里写图片描述

这里写图片描述

3、富文本添加图片代码

// ViewController.m
// 测试富文本
//
// Created by joyshow on 2018/7/10.
// Copyright © 2018年 石虎. All rights reserved.

#import "ViewController.h"
@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];


    //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;
}

@end

4、富文本总结

这是富文本的全部属性web

属性Name 干啥的 类型
NSFontAttributeName 字号 UIFont 默认12
NSParagraphStyleAttributeName 段落样式 NSParagraphStyle
NSForegroundColorAttributeName 前景色 UIColor
NSBackgroundColorAttributeName 背景色 UIColor
NSObliquenessAttributeName 字体倾斜 NSNumber
NSExpansionAttributeName 字体加粗 NSNumber 比例 0就是不变 1增长一倍
NSKernAttributeName 字间距 CGFloat
NSUnderlineStyleAttributeName 下划线 1或0
NSUnderlineColorAttributeName 下划线颜色 UIColor
NSStrikethroughStyleAttributeName 删除线 1或0
NSStrikethroughColorAttributeName 删除线颜色 UIColor
NSStrokeColorAttributeName same as ForegroundColor UIColor
NSStrokeWidthAttributeName 字体描边 CGFloat
NSLigatureAttributeName 连笔字 没看出效果 1或0
NSShadowAttributeName 阴影 NSShawdow
NSTextEffectAttributeName 设置文本特殊效果,目前只有图版印刷效果可用 NSString
NSAttachmentAttributeName 设置文本附件,经常使用插入图片 NSTextAttachment
NSLinkAttributeName 连接 NSURL (preferred) or NSString
NSBaselineOffsetAttributeName 基准线偏移 NSNumber
NSWritingDirectionAttributeName 文字方向 分别表明不一样的文字出现方向等等,我想你必定用不到它 - - @[@(1),@(2)]
NSVerticalGlyphFormAttributeName 水平或者竖直文本 在iOS没卵用,不支持竖版 1竖直 0水平