gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:17:01 26 4
gpt4 key购买 nike

我有 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 的委托(delegate)方法中重置受影响的 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()
}

关于swift - 如何在 Swift 3 的 DTCoreText 中显示与 html 内联的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45298939/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com