Как замаскировать текст UILabel или UITextView? - PullRequest
1 голос
/ 10 июня 2019

Я бы хотел замаскировать текст UILabel для достижения следующего результата

enter image description here

Ответы [ 2 ]

0 голосов
/ 10 июня 2019

Это будет работать для вас.

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
        }
    }

   //you can remove the image by calling this function
    func removeImage()
    {
        let text = self.text
        self.attributedText = nil
        self.text = text
    }
}
0 голосов
/ 10 июня 2019

В Swift Вы можете сделать это так:

var attributedString = NSMutableAttributedString(string: "Your String")

let textAttachment = NSTextAttachment()
textAttachment.image = UIImage(named: "Your Image Name")

let attrStringWithImage = NSAttributedString(attachment: textAttachment)
attributedString.insert(attrStringWithImage, at: 0)

label.attributedText = attributedString
...