onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
677 stars 33 forks source link

How to add trailing image to UILabel in iOS #470

Open onmyway133 opened 5 years ago

onmyway133 commented 5 years ago

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

the image parameter should be optional

ielyas commented 2 years ago

the image parameter should be optional

@jianpx could you elaborate on that?