How to add trailing image to UILabel in iOS

Issue #470

Use NSTextAttachment inside NSAttributedString

extension UILabel {
    func addTrailing(image: UIImage) {
        let attachment = NSTextAttachment()
        attachment.image = image

        let attachmentString = NSAttributedString(attachment: attachment)
        let string = NSMutableAttributedString(string: self.text!, attributes: [:])

        string.append(attachmentString)
        self.attributedText = string
    }
}
Written by

I’m open source contributor, writer, speaker and product maker.

Start the conversation