这是您可以做的事情。
注意:我不是 Swift 开发者,更像是 Objective-C 开发者,所以可能会有一些丑陋的 Swift 代码(thetry!
等)。但更多的是关于使用的逻辑NSRegularExpression
(我在 Objective-C 中使用过,因为它在 CocoaTouch 中共享)
所以主线指令:
查找图像占位符在哪里。
从它创建一个NSAttributeString
/ NSTextAttachment
。
将占位符替换为之前的属性字符串。
let regPattern = "\\[((.*?).png)\\]"
let regex = try! NSRegularExpression.init(pattern: regPattern, options: [])
let matches = regex.matches(in: attributedStringWithRtf.string, options: [], range: NSMakeRange(0, attributedStringWithRtf.length))
for aMatch in matches.reversed()
{
let allRangeToReplace = attributedStringWithRtf.attributedSubstring(from: aMatch.range(at: 0)).string
let imageNameWithExtension = attributedStringWithRtf.attributedSubstring(from: aMatch.range(at: 1)).string
let imageNameWithoutExtension = attributedStringWithRtf.attributedSubstring(from: aMatch.range(at: 2)).string
print("allRangeToReplace: \(allRangeToReplace)")
print("imageNameWithExtension: \(imageNameWithExtension)")
print("imageNameWithoutExtension: \(imageNameWithoutExtension)")
//Create your NSAttributedString with NSTextAttachment here
let myImageAttribute = ...
attributedStringWithRtf.replaceCharacters(in: imageNameRange, with: myImageAttributeString)
}
那么这个想法是什么?
我使用了修改模式。我硬写了“png”,但你可以改变它。我添加了一些()
以轻松获得有趣的部分。我认为您可能想要检索图像的名称,无论是否带有.png
,这就是我得到所有这些的原因print()
。可能是因为您将其保存在您的应用程序中,等等。如果您需要将扩展程序添加为一个组,您可能希望将其添加到您的括号中regPattern
并检查aMatch.range(at: ??)
要调用的内容。用于使用Bundle.main.url(forResource: imageName, withExtension: imageExtension)
我使用了,matches.reversed()
因为如果你用不同长度的替换来修改“匹配”的长度,之前的范围将被关闭。所以从头开始可以做到这一点。
UIImage
将 a转换为NSAttributedString
的一些代码NSTextAttachment
:如何使用 nsattributedstring 在 Swift 中将图像添加为文本附件