AsyncTextAttachment并不能很好的支持UILabel, 将Demo中的UITextView替换成UILabel, 无法显示图片,

#142 · open · 5 comments

View on GitHub ↗

lixiang1994

UILabel: <img width="366" alt="label" src="https://user-images.githubusercontent.com/13112992/164968309-68498626-77c9-4a7a-8ea2-7054608faa50.png"> UITextView: <img width="366" alt="textview" src="https://user-images.githubusercontent.com/13112992/164968306-b6b9aefb-9c73-4fd1-a01c-8b5e26aae131.png">

Comments

lixiang1994

<img width="1400" alt="WX20220424-170717@2x" src="https://user-images.githubusercontent.com/13112992/164969021-ab1e0afd-cb13-4d22-a35b-4bc9bae4f549.png">

bohdan-ios

"UILabel uses an internal NSLayoutManager for laying out the text and drawing it. Unfortunately Apple does not provide a property for us to access or customize it." [Source](https://www.cocoanetics.com/2015/03/customizing-uilabel-hyperlinks/) I use a trick reload ```attributedText``` after the attachment has been loaded: ``` extension UILabel { func reloadAttributedText() { let attr = attributedText attributedText = nil attributedText = attr } } ``` Hope it helps!

midhunmgopal

Hi @Bochbo, could you please explain a little more about how this `reloadAttributedText()` method got called? I am also facing a situation where the image is downloading but it is not reflecting on the UI.

bohdan-ios

Hello, @midhunmgopal Call `reloadAttributedText()` after the delegate method `textAttachmentDidLoadImage` called. See the code example below. <details> <summary><mark><font color=darkred>Code example</font></mark> </summary> <p> ```swift class ViewController: UIViewController { private let label = UILabel() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .black configureLabel() let imageURL = "https://shorturl.at/GNV01" let attributedString = NSMutableAttributedString(imageURL: imageURL, delegate: self) label.attributedText = attributedString } private func configureLabel() { view.addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ label.topAnchor.constraint(equalTo: view.topAnchor, constant: 16), label.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16), label.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -16), label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16), ]) } } extension ViewController: AsyncTextAttachmentDelegate { func textAttachmentDidLoadImage(textAttachment: AsyncTextAttachment, displaySizeChanged: Bool) { label.reloadAttributedText() } } extension UILabel { func reloadAttributedText() { let attr = attributedText attributedText = nil attributedText = attr } } ``` </p> </details>

midhunmgopal

Thank you so much @Bochbo ... It worked !!