如果要在富文本中添加图片的话,用UITextKit才能实现。
什么是UITextKit:它就是处理富文本的框架。
什么时候使用UITextKit:比如要实现图文混搭的节目。
在gitHub中 https://github.com/YouXianMing/BookTextView 可以下载一个关于UITextKit的Demo。
以下是ViewController中的类:
1 #import "ViewController.h" 2 #import "ParagraphAttributes+Constructor.h" 3 #import "ExclusionView.h" 4 #import "BookTextView.h" 5 6 #define Width [UIScreen mainScreen].bounds.size.width 7 #define Height [UIScreen mainScreen].bounds.size.height 8 9 @interface ViewController ()<UITextViewDelegate> 10 11 @property (strong, nonatomic) BookTextView *bookView; 12 13 @end 14 15 @implementation ViewController 16 17 - (void)viewDidLoad { 18 [super viewDidLoad]; 19 20 21 // 读取文本 22 NSString *text = [NSString stringWithContentsOfFile:[NSBundle.mainBundle URLForResource:@"lorem" withExtension:@"txt"].path 23 encoding:NSUTF8StringEncoding 24 error:nil]; 25 26 27 // 初始化bookView 28 self.bookView = [[BookTextView alloc] initWithFrame:CGRectMake(10, 10, Width - 20, Height - 20)]; 29 self.bookView.textString = text; 30 31 // 设置段落样式 32 self.bookView.paragraphAttributes = [ParagraphAttributes qingKeBengYue]; 33 34 // 设置富文本 35 self.bookView.attributes = @[[ConfigAttributedString foregroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.75f] 36 range:NSMakeRange(0, 9)], 37 [ConfigAttributedString font:[UIFont fontWithName:QingKeBengYue size:22.f] 38 range:NSMakeRange(0, 9)]]; 39 40 // 加载图片 41 ExclusionView *exclusionView = [[ExclusionView alloc] initWithFrame:CGRectMake(150.f, 195, 320, 150)]; 42 self.bookView.exclusionViews = @[exclusionView]; 43 UIImageView *imageView = [[UIImageView alloc] initWithFrame:exclusionView.bounds]; 44 imageView.image = [UIImage imageNamed:@"demo"]; 45 [exclusionView addSubview:imageView]; 46 47 48 // 构建view 49 [self.bookView buildWidgetView]; 50 [self.view addSubview:self.bookView]; 51 52 53 // 延时0.01s执行 54 [self performSelector:@selector(event) 55 withObject:nil 56 afterDelay:0.01]; 57 } 58 59 - (void)event { 60 [self.bookView moveToTextPercent:0.00]; 61 } 62 63 @end