Ios 如何屏蔽UILabel或UITextView的文本?
我想屏蔽UILabel的文本以实现以下结果Ios 如何屏蔽UILabel或UITextView的文本?,ios,swift,uiimageview,uilabel,uitextview,Ios,Swift,Uiimageview,Uilabel,Uitextview,我想屏蔽UILabel的文本以实现以下结果 在Swift中,您可以这样做: var attributedString = NSMutableAttributedString(string: "Your String") let textAttachment = NSTextAttachment() textAttachment.image = UIImage(named: "Your Image Name") let attrStringWithImage = NSAttributedStr
在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
这对你有用
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
}
}
为此,请使用UITextView
而不是UILabel
let imgRectBezier = UIBezierPath(rect: imgView.frame)
txtView.textContainer.exclusionPaths = [imgRectBezier]
使用此选项,文本将从添加到排除路径中的框架区域中排除。您甚至可以排除多个帧。我想这就是您的意思: