iOS 7 TextKit - 如何插入带有文本的图像? [英] iOS 7 TextKit - How to insert images inline with text?

查看:16
本文介绍了iOS 7 TextKit - 如何插入带有文本的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 UITextView 获得以下效果:

I am trying to get the following effect using a UITextView:

基本上我想在文本之间插入一个图像.图像可以简单地只占用 1 行空间,因此不需要换行.

Basically I want to insert an image between text. The image can simply just take up 1 row of space so there is no wrapping necessary.

我试着在子视图中添加一个 UIView:

I tried just adding a UIView to the subview:

UIView *pictureView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
[pictureView setBackgroundColor:[UIColor redColor]];
[self.textView addSubview:pictureView];

但它似乎漂浮在文本上并覆盖它.

But it seems to float over the text and cover it.

我对排除路径做了一些阅读,这似乎是实现这一点的一种方式.但是,我不想绝对定位图像 - 相反,它应该与文本一起流动(类似于 在 HTML 中的行为方式).

I did a bit of reading on exclusion paths which appears to be one way of implementing this. However, I don't want to absolutely position the image - instead, it should flow with the text (similar to how <span> behaves in HTML).

推荐答案

您需要使用属性字符串并将图像添加为 NSTextAttachment 的实例:

You'll need to use an attributed string and add the image as instance of NSTextAttachment:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"like after"];

NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:@"whatever.png"];

NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];

[attributedString replaceCharactersInRange:NSMakeRange(4, 1) withAttributedString:attrStringWithImage];

这篇关于iOS 7 TextKit - 如何插入带有文本的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆