Search code examples
iosnsattributedstringnsparagraphstyle

How to center image in attributed string?


I have an image that I want to center alongside a bunch of text but even when I set the NSMutableParagraphStyle alignment to center, the line with the image does not center

enter image description here

If anyone could please help me center the line with the image (i.e. first line) that would be great!

Code

let text = " text next to image is not centered \n\n centered text \n more centered text"
let iconAttachment = textAttachment(fontSize: 14, image: #imageLiteral(resourceName: "icon"))
        let iconString = NSAttributedString(attachment: iconAttachment)
let style = NSMutableParagraphStyle()
        style.alignment = .center
        style.minimumLineHeight = 20
        
        let attributedText = NSMutableAttributedString()
        attributedText.append(iconString)
        let fullText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName : style])
        attributedText.append(fullText)

private func textAttachment(fontSize: CGFloat, image: UIImage) -> NSTextAttachment {
        let font = UIFont.systemFont(ofSize: fontSize) //set accordingly to your font, you might pass it in the function
        let textAttachment = NSTextAttachment()
            textAttachment.image = image
        let mid = font.descender + font.capHeight
        textAttachment.bounds = CGRect(x: 0, y: font.descender - image.size.height / 2 + mid + 2, width: image.size.width, height: image.size.height).integral
        return textAttachment
    }

Solution

  • You just need to Alignment your lebel text to center and it will work :

     label.textAlignment = .center
    

    enter image description here