我正在尝试使用UITextView来获得以下效果:
基本上,我想在文本之间插入一个图像。该图像可以简单地占用一行空间,因此没有必要进行包装。
我只是尝试在子视图中添加一个UIView:
UIView *pictureView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
[pictureView setBackgroundColor:[UIColor redColor]];
[self.textView addSubview:pictureView];
但它似乎漂浮在文本上,并覆盖了它。
我在排除路径上做了一些阅读,它似乎是实现这一点的一种方式。然而,我不想绝对地定位图像-相反,它应该与文本一起排列(类似于<span>
在超文本标记语言中的行为)。
发布于 2014-01-05 13:57:28
您需要使用属性字符串并将图像添加为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];
发布于 2016-01-20 06:52:58
@bilobatum的代码转换为Swift,供有需要的人使用:
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)
发布于 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/
在我的示例中,我调整了图像的大小以适应宽度,在您的示例中,您可能希望调整图像的大小以匹配线条高度。
https://stackoverflow.com/questions/20930462
复制相似问题