Ognjen Koprivica
Ognjen Koprivica

Reputation: 57

How to insert custom emoji in UILabel programmatically, in Swift?

I am building an iOS app where I have to add support for emojis within UILabel, so basically, whenever I receive a string containing either of these:

[kick-off]
[yellow-card]
[red-card]
[introduce]
[substitute]
[attention]
[free-kick]
[penalty]
[offside]
[extra-time]
[throw-in]
[corner]
[goal-post]
[bar]
[cheers]
[goal]

I have to replace these tags with a corresponding emoji. I have custom images for these emojis:

https://cdn-waf-beta.global.ssl.fastly.net/0.55.12/static/images/WAF_live_icons_sprite.png

Any idea how could I pull that off using Swift?

Upvotes: 1

Views: 3035

Answers (2)

Markv07
Markv07

Reputation: 272

Here is the latest (swift v5) syntax with a few additions:

func strgWithImage(yourImage: String, preImage: String, postImage: String) -> NSMutableAttributedString {
// Call function with attributed text label:
// testLabel.attributedText = strgWithImage(yourImage: "doneX.png", preImage: "preS", postImage: "postS")
let stringAttributes = [
    // insert any attributes here
    NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14)
    ,NSAttributedString.Key.foregroundColor : UIColor.black
]
let attributedString = NSMutableAttributedString(string: preImage, attributes: stringAttributes)
let postString = NSMutableAttributedString(string: postImage, attributes: stringAttributes)
let attachment = NSTextAttachment()
attachment.image = UIImage(named:yourImage) // loaded in assets
let imageOffsetY: CGFloat = -15.0
attachment.bounds = CGRect(x: 0, y: imageOffsetY, width: attachment.image!.size.width, height: attachment.image!.size.height)
let attachmentString = NSAttributedString(attachment: attachment)
attributedString.append(attachmentString)
attributedString.append(postString)
return attributedString

}

Upvotes: 0

Aaron Bannin
Aaron Bannin

Reputation: 127

You need to create an NSTextAttachment and append it to an NSAttributedString.

Example:

let stringAttributes = [
    // insert any attributes here
    NSFontAttributeName : UIFont.systemFontOfSize(14)
    ,NSForegroundColorAttributeName : UIColor.blackColor()
]
let attributedString = NSMutableAttributedString(string: "the string before your image ", attributes: stringAttributes)

// Image needs to be NSData
let imageData:NSData = UIImagePNGRepresentation(yourImage)!
// Attachment type is very important
let attachment = NSTextAttachment(data: imageData, ofType: "public.png")
let attachmentString = NSAttributedString(attachment: attachment)
attributedString.appendAttributedString(attachmentString)

print(attributedString)

You can find the appropriate uti (Uniform Type Identifier) here

Upvotes: 1

Related Questions