Search code examples
iosswiftuikitios15textkit

iOS 15 image attachment behaviour to NSAttributedString is different. How can I fix the height of the label?


On iOS 14 when attaching an image to a NSAttributedString the resulting height of the label is correct, however on iOS 15 it is too tall.

iOS 14:

enter image description here

iOS 15: enter image description here

Code:

view.backgroundColor = .black


label.layer.borderColor = UIColor.red.cgColor

label.layer.borderWidth = 1


let font = UIFont.systemFont(ofSize: 11, weight: .bold)

let text = NSMutableAttributedString(string: "LIVE", attributes: [.foregroundColor: UIColor.systemGreen, .font: font])


let attachment = NSTextAttachment()

attachment.image = UIImage(named: "live_indicator_image")!

let imageString = NSMutableAttributedString(attachment: attachment)

text.append(imageString)


label.attributedText = text

Image:

enter image description here

Xcode version: 13.1

Simulators: iPhone 13 (15.0), iPhone 12 (14.4)


Solution

  • I have similar problem on my project that displayed well on iOS14 or former but wrong on iOS15. In order to fix this, I added font attribute to the NSMutableAttributedString made with NSTextAttachment right before appending to the final text as below. Please try.

    let attachment = NSTextAttachment()
    
    attachment.image = UIImage(named: "live_indicator_image")!
    
    let imageString = NSMutableAttributedString(attachment: attachment)
    
    imageString.addAttribute(.font, value: font, range: NSRange(location: 0, length:imageString.length))
    
    text.append(imageString)