我正在创建一个聊天应用程序,我正在插入啤酒图标的字段不会渲染图像或似乎没有内嵌渲染图像.我没有收到任何错误,所以我假设我在代码中遗漏了一些小细节.
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 }}总结
以上是内存溢出为你收集整理的如何使用swift在iOS 8中插入图像内联UILabel全部内容,希望文章能够帮你解决如何使用swift在iOS 8中插入图像内联UILabel所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)