如何隐藏UILabel或UITextView的文本?

时间:2019-06-10 08:31:11

标签: ios swift uilabel uitextview

我想屏蔽UILabel的文本以获得以下结果

enter image description here

3 个答案:

答案 0 :(得分:0)

在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

答案 1 :(得分: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
        }
    }

   //you can remove the image by calling this function
    func removeImage()
    {
        let text = self.text
        self.attributedText = nil
        self.text = text
    }
}

答案 2 :(得分:0)

enter image description here

为此,请使用UITextView而不是UILabel

let imgRectBezier = UIBezierPath(rect: imgView.frame)
txtView.textContainer.exclusionPaths = [imgRectBezier]

使用此方法,将从排除路径中添加的框架区域中排除文本。您甚至可以排除多个帧。