【问题标题】:How can I add a custom view to an attributed string or text view?如何将自定义视图添加到属性字符串或文本视图?
【发布时间】:2017-05-23 23:09:09
【问题描述】:

我正在尝试获取属性字符串中的自定义视图以显示在 textView 上。我可以添加带有 NSTextAttachment 的图像,但这不是我想要的。我有一个自定义视图,它支持我想在文本之间显示的 Gif 和动画 PNG。

例子:

文本文本文本[customView] 文本[customView] 文本。

我希望得到一些关于我应该在哪里进行具体搜索的指导。到目前为止,我已经看到了相关的问题...

【问题讨论】:

  • NSAttributedString 不是视图类。它直接继承自 NSObject。要么您的问题具有误导性,要么您走错了通往目标的道路。你能解释一下你想要达到的目标吗?
  • @d00dle 我想 1) 确定是否可以像使用 UIImage 一样将 UIView 放入属性字符串中。 2)如果没有,弄清楚我应该怎么做才能让我的 UIView 在文本视图中与文本内联。例如,一种解决方案可能是获取 uiView 的“屏幕截图”,并将其制作为 uiimage,然后将该图像通过文本附件放入属性字符串中。但这不会保留动画,所以我需要在其中获取这个实际的自定义 UIView

标签: ios swift uitextview nsattributedstring nstextattachment


【解决方案1】:

首先,使用NSAttributedStringNSMutableAttributedString 在子视图中显示您的 RichText(如 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];

顺便说一句:如果您使用YYkit 为RichText,则不能使用YYAttachMentString 替换NSAttachMentString,这些是不同的东西,UITextView(UILabel) 无法加载YYAttachMentString。 我正在寻找某种方式来使用UITextView 显示我的 gif(因为YYKit 无法使用 url 加载和预览网络图像,YYKit 总是显示为空,应该是 netImage,cripes!)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多