如何将自定义视图添加到属性字符串或文本视图中?

3
我正在尝试在textView上显示一个自定义视图的属性字符串。我可以使用NSTextAttachment添加图像,但这不是我想要的。我有一个支持Gif和Animated PNG的自定义视图,我想在文本之间显示它。
示例: 文本文本文本[customView]文本[customView]文本。 <- 最好在属性字符串中
我希望能得到一些具体搜索方向的指导。到目前为止,我已经看到了相关的问题...
- 子类化NSTextAttachment: 如何子类化NSTextAttachment? - 使用NSTextAttachmentContainer..? - NSTextAttachmentCell - 仅限OSX - 在文本视图中进行操作

1
NSAttributedString不是视图类,它直接继承自NSObject。你的问题可能有误导性,或者你走错了方向来实现你的目标。你能解释一下你想要达到什么吗? - d00dle
1
@d00dle 我想要做两件事情:1)确定我是否可以像UIImage一样将UIView放入属性字符串中。2)如果不行,找出应该怎么做才能让我的UIView与文本在文本视图中内联。例如,一个解决方案可能是对uiView进行“截屏”,并将其制作为uiimage,然后通过文本附件将该图像放入属性字符串中。但这样做无法保留动画效果,所以我需要将这个实际的自定义UIView放入其中。 - james VB
1个回答

0
首先,使用NSAttributedStringNSMutableAttributedString在子视图中显示您的富文本(例如UITextView/UILabel)。
然后,使用NSTextAttachment替换文本中的图像脚本。
NSString *egText = @"hello [this_is_an_img_script]";

NSMutableAttributedString * destStr = [[NSMutableAttributedString alloc] initWithString:egText];

NSTextAttachment *attachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil];

attachment.image = [UIImage imageNamed:[this_is_an_img_script]];

NSAttributedString *textAttachmentString = [NSAttributedString attributedStringWithAttachment:attachment]; //make your image to an attributedString

[destStr replaceCharactersInRange:range withAttributedString:textAttachmentString];

at last: [YourLabel(or YourTextView) setAttributedString:destStr];

顺便说一下:如果您在RichText中使用YYkit,就不能使用YYAttachMentString来替换NSAttachMentString,因为它们是不同的东西。UITextView(UILabel)无法加载YYAttachMentString。我正在寻找一种方法来在UITextView中显示我的gif(因为YYKit无法通过url加载和预览netimage,YYKit总是显示应该是netImage的空白!)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接