如何在 Swift 3 中的 DTCoreText 中显示与 html 内联的图像

How to show image inline with html in DTCoreText in Swift 3

我有 DTAttributedTextContentView,我在其中成功呈现来自 HTML 的文本。现在我想嵌入一张与文本内联显示的图片。我查看了文档,只有 Objective-C 个示例。如何在 Swift:

上做同样的事情

显示远程图像的最佳方式是使用 DTLazyImageView。首先,您需要 return DTLazyImageView 实例作为图像附件。

- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttachment:(DTTextAttachment *)attachment frame:(CGRect)frame
{
    if([attachment isKindOfClass:[DTImageTextAttachment class]])
     {
        DTLazyImageView *imageView = [[DTLazyImageView alloc] initWithFrame:frame];
        imageView.delegate = self;

        // url for deferred loading
        imageView.url = attachment.contentURL;
        return imageView;
    }
    return nil;
}

然后在 DTLazyImageView 的委托方法中重置受影响的 DTAtributedContextView 的布局。

- (void)lazyImageView:(DTLazyImageView *)lazyImageView didChangeImageSize:(CGSize)size 
{
    NSURL *url = lazyImageView.url;
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"contentURL == %@", url];

    // update all attachments that matching this URL
    for (DTTextAttachment *oneAttachment in [self.attributedTextContentView.layoutFrame textAttachmentsWithPredicate:pred]) 
     {
        oneAttachment.originalSize = size;
    }

    // need to reset the layouter because otherwise we get the old framesetter or cached layout frames
    self.attributedTextContentView.layouter = nil;

    // here we're layouting the entire string,
    // might be more efficient to only relayout the paragraphs that contain these attachments
    [self.attributedTextContentView relayoutText];
}

similar question is here

我在最后重写了 Swift 3 语法:

  @IBOutlet weak var textLabel: DTAttributedTextContentView!


        func attributedTextContentView(viewForAttachment: DTAttributedTextContentView, attachment: DTTextAttachment, frame: CGRect) -> UIView {
            if attachment is DTImageTextAttachment {
                let imageView = DTLazyImageView(frame: frame)
                imageView.delegate = self as! DTLazyImageViewDelegate
                // url for deferred loading
                imageView.url = attachment.contentURL
                return imageView
            }
            return UIView(frame: CGRect.zero)
        }

        func lazyImageView(lazyImageView: DTLazyImageView, didChangeImageSize: CGSize) {
            guard let url = lazyImageView.url else {return}
            let pred = NSPredicate(format: "contentURL == %@", url as CVarArg)

            let array = textLabel.layoutFrame.textAttachments(with: pred)



            for (_, _) in (array?.enumerated())! {
                let element = DTTextAttachment()
                element.originalSize = didChangeImageSize
            }

            textLabel.layouter = nil
            textLabel.relayoutText()
        }