加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何使用swift在iOS 8中插入图像内联UILabel

发布时间:2020-12-14 05:29:35 所属栏目:百科 来源:网络整理
导读:我按照 following post关于如何使用NSTextAttachment添加与UILabel内联的图像.我尽我所能,并在Swift中编写了我的版本. 我正在创建一个聊天应用程序,我正在插入啤酒图标的字段不会渲染图像或似乎没有内嵌渲染图像.我没有收到任何错误,所以我假设我在代码中遗
我按照 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
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读