在iOS Swift中将图像添加到文本背景中

时间:2018-02-15 09:21:22

标签: swift3 uitextfield nsattributedstring nsmutableattributedstring

在我的应用程序中,我需要将图像显示为字符串中特定字符的背景。 Swift有可能吗?我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

我想你正在使用UILabel。所以试着这样做:

// Create an NSMutableAttributedString
let mainString = NSMutableAttributedString(string: "Your Text")

// Create NSTextAttachment
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(named: "image.png")

// Attachment imageAttachment to NSAttributedString
let imageString = NSAttributedString(attachment: imageAttachment)

// Add the NSTextAttachment to the mainString
mainString.append(imageString)
mainString.append(NSAttributedString(string: "End"))

// Set the result in your label
yourLabel.attributedText = mainString

我希望这可以帮到你。