简体   繁体   中英

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?

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM