malcommac / SwiftRichString

👩‍🎨 Elegant Attributed String composition in Swift sauce
MIT License
3.1k stars 211 forks source link

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

Open lixiang1994 opened 2 years ago

lixiang1994 commented 2 years ago

UILabel:

label

UITextView:

textview
lixiang1994 commented 2 years ago
WX20220424-170717@2x
swiftyuser commented 2 years ago

"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

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 commented 2 years ago

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.

swiftyuser commented 2 years ago

Hello, @midhunmgopal

Call reloadAttributedText() after the delegate method textAttachmentDidLoadImage called. See the code example below.

Code example

```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 } } ```

midhunmgopal commented 2 years ago

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