metatext/Views/UIKit/AnimatedAttachmentLabel.swift

56 lines
1.8 KiB
Swift
Raw Normal View History

2021-02-22 07:10:34 +00:00
// Copyright © 2021 Metabolist. All rights reserved.
2021-02-22 23:59:33 +00:00
import SDWebImage
2021-02-22 07:10:34 +00:00
import UIKit
final class AnimatedAttachmentLabel: UILabel, EmojiInsertable {
override init(frame: CGRect) {
super.init(frame: frame)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawText(in rect: CGRect) {
super.drawText(in: rect)
guard let attributedText = attributedText else { return }
2021-02-22 23:59:33 +00:00
var attachmentImageViews = Set<SDAnimatedImageView>()
2021-02-22 07:10:34 +00:00
attributedText.enumerateAttribute(
.attachment,
in: NSRange(location: 0, length: attributedText.length),
options: .longestEffectiveRangeNotRequired) { attachment, _, _ in
2022-05-06 02:29:05 +00:00
guard let animatedAttachment = attachment as? AnimatedTextAttachment,
let imageBounds = animatedAttachment.imageBounds
else { return }
2021-02-22 07:10:34 +00:00
2022-05-06 02:29:05 +00:00
animatedAttachment.imageView.frame = imageBounds
2021-02-22 07:10:34 +00:00
2022-05-06 02:29:05 +00:00
// iOS 15 needs this for some inexplicable reason
if #available(iOS 15, *) {
animatedAttachment.imageView.frame.origin.y -= font.lineHeight
}
2022-05-06 02:29:05 +00:00
animatedAttachment.imageView.contentMode = .scaleAspectFit
if animatedAttachment.imageView.superview != self {
addSubview(animatedAttachment.imageView)
}
attachmentImageViews.insert(animatedAttachment.imageView)
}
for subview in subviews {
guard let attachmentImageView = subview as? SDAnimatedImageView else { continue }
if !attachmentImageViews.contains(attachmentImageView) {
attachmentImageView.removeFromSuperview()
}
2021-02-22 07:10:34 +00:00
}
}
}