我按照
following post关于如何使用NSTextAttachment添加与UILabel内联的图像.我尽我所能,并在Swift中编写了我的版本.
我正在创建一个聊天应用程序,我正在插入啤酒图标的字段不会渲染图像或似乎没有内嵌渲染图像.我没有收到任何错误,所以我假设我在代码中遗漏了一些小细节.
var beerName:String! if(sender == bn_beer1) { beerName = "beer1.png" } if(sender == bn_beer2) { beerName = "beer2.png" } if(sender == bn_beer3) { beerName = "beer3" } var attachment:NSTextAttachment = NSTextAttachment() attachment.image = UIImage(named: beerName) var attachmentString:NSAttributedString = NSAttributedString(attachment: attachment) var myString:NSMutableAttributedString = NSMutableAttributedString(string: inputField.text) myString.appendAttributedString(attachmentString) inputField.attributedText = myString;
这不适用于UITextField.它只适用于UILabel.
这是基于您的代码的UILabel扩展(Swift 2.0)
extension UILabel { func addImage(imageName: String) { let attachment:NSTextAttachment = NSTextAttachment() attachment.image = UIImage(named: imageName) let attachmentString:NSAttributedString = NSAttributedString(attachment: attachment) let myString:NSMutableAttributedString = NSMutableAttributedString(string: self.text!) myString.appendAttributedString(attachmentString) self.attributedText = myString } }
编辑:
这是一个新版本,允许在标签之前或之后添加图标.还有一个从标签中删除图标的功能
extension UILabel { func addImage(imageName: String,afterLabel bolAfterLabel: Bool = false) { let attachment: NSTextAttachment = NSTextAttachment() attachment.image = UIImage(named: imageName) let attachmentString: NSAttributedString = NSAttributedString(attachment: attachment) if (bolAfterLabel) { let strLabelText: NSMutableAttributedString = NSMutableAttributedString(string: self.text!) strLabelText.appendAttributedString(attachmentString) self.attributedText = strLabelText } else { let strLabelText: NSAttributedString = NSAttributedString(string: self.text!) let mutableAttachmentString: NSMutableAttributedString = NSMutableAttributedString(attributedString: attachmentString) mutableAttachmentString.appendAttributedString(strLabelText) self.attributedText = mutableAttachmentString } } func removeImage() { let text = self.text self.attributedText = nil self.text = text } }