0

在我的 iOS/swift 项目中,我使用下面的代码将 RTF 文档加载到 UITextView。RTF 本身包含样式文本,例如“... blah blah [ABC.png] blah blah [DEF.png] blah ...”,可以很好地加载到 UITextView。

现在,我想将所有出现的 [someImage.png] 替换为 NSTextAttachment 的实际图像。我怎样才能做到这一点?

我知道在 RTF 文档中嵌入图像的可能性,但在这个项目中我不能这样做。

if let rtfPath = Bundle.main.url(forResource: "testABC", withExtension: "rtf") 
{
    do
    {
    //load RTF to UITextView
    let attributedStringWithRtf = try NSAttributedString(url: rtfPath, options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
    txtView.attributedText = attributedStringWithRtf

    //find all "[ABC.png]" and replace with image
    let regPattern = "\\[.*?\\]"
    //now...?
    }
}
4

1 回答 1

0

这是您可以做的事情。

注意:我不是 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 中将图像添加为文本附件

于 2017-11-20T09:04:48.717 回答