2021-02-22 08:10:34 +01:00
|
|
|
// Copyright © 2021 Metabolist. All rights reserved.
|
|
|
|
|
2021-02-23 00:59:33 +01:00
|
|
|
import SDWebImage
|
2021-02-22 08:10:34 +01:00
|
|
|
import UIKit
|
|
|
|
|
|
|
|
final class AnimatingLayoutManager: NSLayoutManager {
|
|
|
|
weak var view: UIView?
|
|
|
|
|
|
|
|
override func drawGlyphs(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint) {
|
|
|
|
guard let textStorage = textStorage else {
|
|
|
|
super.drawGlyphs(forGlyphRange: glyphsToShow, at: origin)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-02-23 00:59:33 +01:00
|
|
|
var attachmentImageViews = Set<SDAnimatedImageView>()
|
2021-02-22 08:10:34 +01:00
|
|
|
|
|
|
|
textStorage.enumerateAttribute(
|
|
|
|
.attachment,
|
|
|
|
in: NSRange(location: 0, length: textStorage.length)) { attachment, _, _ in
|
2021-02-23 03:51:31 +01:00
|
|
|
guard let animatedAttachment = attachment as? AnimatedTextAttachment,
|
|
|
|
let imageBounds = animatedAttachment.imageBounds
|
|
|
|
else { return }
|
|
|
|
|
|
|
|
animatedAttachment.imageView.frame = imageBounds
|
|
|
|
animatedAttachment.imageView.contentMode = .scaleAspectFit
|
|
|
|
|
|
|
|
if animatedAttachment.imageView.superview != view {
|
|
|
|
view?.addSubview(animatedAttachment.imageView)
|
|
|
|
}
|
2021-02-22 08:10:34 +01:00
|
|
|
|
2021-02-23 03:51:31 +01:00
|
|
|
attachmentImageViews.insert(animatedAttachment.imageView)
|
2021-02-22 08:10:34 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
for subview in view?.subviews ?? [] {
|
2021-02-23 00:59:33 +01:00
|
|
|
guard let attachmentImageView = subview as? SDAnimatedImageView else { continue }
|
2021-02-22 08:10:34 +01:00
|
|
|
|
|
|
|
if !attachmentImageViews.contains(attachmentImageView) {
|
|
|
|
attachmentImageView.removeFromSuperview()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
super.drawGlyphs(forGlyphRange: glyphsToShow, at: origin)
|
|
|
|
}
|
|
|
|
}
|