我关注了 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
}
}
关于swift - 如何使用 swift 在 iOS 8 中插入图像 Inline UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26744444/