diff --git a/Sources/AttributedText/AttributedText_AppKit.swift b/Sources/AttributedText/AttributedText_AppKit.swift index bb06fe8..d5cf43f 100644 --- a/Sources/AttributedText/AttributedText_AppKit.swift +++ b/Sources/AttributedText/AttributedText_AppKit.swift @@ -77,7 +77,9 @@ override func layout() { super.layout() + textView.frame = bounds + textView.attributedString().updateImageTextAttachments(maxWidth: bounds.width) } override func invalidateIntrinsicContentSize() { diff --git a/Sources/AttributedText/AttributedText_UIKit.swift b/Sources/AttributedText/AttributedText_UIKit.swift index 570a9a5..24ba90e 100644 --- a/Sources/AttributedText/AttributedText_UIKit.swift +++ b/Sources/AttributedText/AttributedText_UIKit.swift @@ -69,7 +69,9 @@ override func layoutSubviews() { super.layoutSubviews() + textView.frame = bounds + textView.attributedText.updateImageTextAttachments(maxWidth: bounds.width) } override func invalidateIntrinsicContentSize() { diff --git a/Sources/AttributedText/NSAttributedString+TextAttachment.swift b/Sources/AttributedText/NSAttributedString+TextAttachment.swift new file mode 100644 index 0000000..c2b4fef --- /dev/null +++ b/Sources/AttributedText/NSAttributedString+TextAttachment.swift @@ -0,0 +1,20 @@ +#if os(macOS) + import AppKit +#elseif canImport(UIKit) + import UIKit +#endif + +extension NSAttributedString { + func updateImageTextAttachments(maxWidth: CGFloat) { + enumerateAttribute(.attachment, in: NSRange(location: 0, length: length), options: []) { value, _, _ in + guard let attachment = value as? NSTextAttachment, + let image = attachment.image else { return } + + let aspectRatio = image.size.width / image.size.height + let width = min(maxWidth, image.size.width) + let height = width / aspectRatio + + attachment.bounds = CGRect(x: 0, y: 0, width: width, height: height) + } + } +}