Last active
November 13, 2021 02:26
-
-
Save swhitty/2ea8648f31c27dd5bff35c20f7e692a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension NSAttributedString { | |
/// Iterates over all embedded `UIImage` instances within the string, updating the configuration | |
/// to include the provided `UITraitCollection`. | |
/// | |
func updatingImageAttachments(to traitCollection: UITraitCollection) -> NSAttributedString { | |
var updatedImages = [(Int, UIImage)]() | |
enumerateAttributes(in: NSRange(location: 0, length: length), options: .init(rawValue: 0)) { attributes, range, _ in | |
if let attachment = attributes[.attachment] as? NSTextAttachment, | |
let image = attachment.image ?? attachment.image(forBounds: .zero, textContainer: nil, characterIndex: 0), | |
let configuration = image.configuration { | |
let newImage = image.withConfiguration(configuration.withTraitCollection(traitCollection)) | |
updatedImages.append((range.location, newImage)) | |
} | |
} | |
guard !updatedImages.isEmpty else { return self } | |
let copy = NSMutableAttributedString(attributedString: self) | |
for (index, image) in updatedImages { | |
var attributes = copy.attributes(at: index, effectiveRange: nil) | |
attributes[.attachment] = NSTextAttachment(image: image) | |
copy.setAttributes(attributes, range: NSRange(location: index, length: 1)) | |
} | |
return NSAttributedString(attributedString: copy) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment