带有图像切割图像的Swift属性标签

时间:2019-04-17 23:08:44

标签: ios swift uilabel nsattributedstring

我正在尝试使用一个在其末尾带有图像的标签。问题在于,每当将属性图像添加到标签时,就会切割图像的最后一部分,就像标签的边界将图像剪切到其边界一样:

我试图更改标签的尺寸宽度,但这没用。

用于添加图片的属性文本扩展名的代码为:

我通过以下方式设置标签的值: self.nameLabel.set(image: #imageLiteral(resourceName: "verified"), with: user.fullName!)

并使用此扩展名:

extension UILabel {
    func set(image: UIImage, with text: String) {
        let attachment = NSTextAttachment()
        attachment.image = image
        attachment.bounds = CGRect(x: 3, y: -3, width: 15, height: 15)
        let attachmentStr = NSAttributedString(attachment: attachment)

        let mutableAttributedString = NSMutableAttributedString()

        let textString = NSAttributedString(string: text, attributes: [.font: self.font])
        mutableAttributedString.append(textString)

        mutableAttributedString.append(attachmentStr)

        self.attributedText = mutableAttributedString
    }
}

我用来解决此问题的代码是:

nameLabel.bounds.size.width = 500 而且我也尝试过 nameLabel.frame.size.width = 500

我得到的最终结果看起来像这样的https://imgur.com/zLiClkk,它的末端似乎被切掉了几个像素。如果有人可以帮助我解决此问题并向我解释我要去哪儿,那将不胜感激!

编辑:我最终只是添加了一个UIImage并使用自动布局将其约束在名称的左侧,我以为我以前曾尝试过但没有用。我必须做一些不同的事情,因为它现在可以工作了。无论如何,仍然可以解决以前的问题!

0 个答案:

没有答案