首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >iOS 7 TextKit -如何插入带有文本的内联图像?

iOS 7 TextKit -如何插入带有文本的内联图像?
EN

Stack Overflow用户
提问于 2014-01-05 13:30:23
回答 5查看 59.5K关注 0票数 110

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

基本上,我想在文本之间插入一个图像。该图像可以简单地占用一行空间,因此没有必要进行包装。

我只是尝试在子视图中添加一个UIView:

代码语言:javascript
复制
UIView *pictureView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
[pictureView setBackgroundColor:[UIColor redColor]];
[self.textView addSubview:pictureView];

但它似乎漂浮在文本上,并覆盖了它。

我在排除路径上做了一些阅读,它似乎是实现这一点的一种方式。然而,我不想绝对地定位图像-相反,它应该与文本一起排列(类似于<span>在超文本标记语言中的行为)。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2014-01-05 13:57:28

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

代码语言:javascript
复制
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];
票数 182
EN

Stack Overflow用户

发布于 2016-01-20 06:52:58

@bilobatum的代码转换为Swift,供有需要的人使用:

代码语言:javascript
复制
let attributedString = NSMutableAttributedString(string: "like after")

let textAttachment = NSTextAttachment()

textAttachment.image = UIImage(named: "whatever.png")

let attrStringWithImage = NSAttributedString(attachment: textAttachment)

attributedString.replaceCharacters(in: NSMakeRange(4, 1), with: attrStringWithImage)
票数 28
EN

Stack Overflow用户

发布于 2014-01-05 13:54:36

您可以尝试使用NSAttributedString和NSTextAttachment。查看以下链接,了解有关自定义NSTextAttachment以调整图像大小的更多详细信息。http://ossh.com.au/design-and-technology/software-development/implementing-rich-text-with-images-on-os-x-and-ios/

在我的示例中,我调整了图像的大小以适应宽度,在您的示例中,您可能希望调整图像的大小以匹配线条高度。

票数 20
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20930462

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档