我有DTAttributedTextContentView,可以在其中成功地从HTML渲染文本。现在,我想嵌入以文字形式显示的图片。我浏览了文档,只有Objective-C示例。如何在Swift上执行相同操作:

显示远程图像的最佳方法是使用DTLazyImageView。首先,您将需要为图像附件返回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的in委托方法中,为受影响的DTAttributedContextView重置布局。

- (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()
        }

09-27 13:33