我正在构建一个iOS应用程序,我必须在UILabel中添加对emojis的支持,所以基本上,每当我收到包含以下任何一个的字符串时:
[kick-off]
[yellow-card]
[red-card]
[introduce]
[substitute]
[attention]
[free-kick]
[penalty]
[offside]
[extra-time]
[throw-in]
[corner]
[goal-post]
[bar]
[cheers]
[goal]
我必须用相应的表情符号替换这些标签。我有这些表情符号的自定义图像:
https://cdn-waf-beta.global.ssl.fastly.net/0.55.12/static/images/WAF_live_icons_sprite.png
我知道如何使用Swift来解决这个问题?
答案 0 :(得分:0)
您需要创建NSTextAttachment
并将其附加到NSAttributedString
。
示例:
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)
您可以找到合适的uti(统一类型标识符)here
答案 1 :(得分:0)
这是最新的 (swift v5) 语法,并添加了一些内容:
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
}