1

I have a NSMutableAttributedString string and a NSTextAttachment() image.

The text displays at the bottom of the image. Is there a way to get the text centered in the image?

    let fullString = NSMutableAttributedString(string: "Acceptance")
    let image1 = NSTextAttachment()
    image1.image = UIImage(named: "pos")

    image1.setImageHeight(height:30)

    let image1String = NSAttributedString(attachment: image1)

    fullString.append(image1String)

I do have a NSTextAttachment extension for scaling the image down and plays no part in why the text isn't centered

extension NSTextAttachment {
func setImageHeight(height: CGFloat) {
    guard let image = image else { return }
    let ratio = image.size.width / image.size.height

    bounds = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: ratio * height, height: height)
}
}

This is what it looks like

enter image description here

EDIT: I got it figured out. I will include this because it m ay help someone else out in the future.

image1.bounds = CGRect(x: 0, y: -10, width: 35, height: 35)
steller
  • 245
  • 3
  • 14
  • Possible duplicate of [Vertically aligning NSTextAttachment in NSMutableAttributedString](https://stackoverflow.com/questions/47844721/vertically-aligning-nstextattachment-in-nsmutableattributedstring) – Tamás Sengel Dec 24 '18 at 02:12
  • I can't get their examples to work. They are not complete. What is font.capHeight? font is not even defined. – steller Dec 24 '18 at 05:13
  • every example doesn't work. Something always in red and things are not defined. What is balanceFont.descender? because its RED and not defined. – steller Dec 24 '18 at 05:16
  • None of those examples compile so you are not helping me – steller Dec 24 '18 at 05:18
  • That link didn't help and absolutely did not answer my questions. None of those examples even compile. – steller Dec 24 '18 at 07:50

0 Answers0