gpt4 book ai didi

ios - Swift:加载样式 RTF 后将字符串替换为 UITextView 中的 NSTextAttachment

转载 作者:行者123 更新时间:2023-11-30 11:59:50 24 4
gpt4 key购买 nike

在我的 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...?
}
}

最佳答案

这是您可以做的事情。

注意:我不是一名 Swift 开发者,更多的是一名 Objective-C 开发者,因此可能会有一些丑陋的 Swift 代码(try! 等)。但更多的是使用 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(),因为如果您用不同长度的替换来修改“匹配”的长度,则先前的范围将被关闭。所以从最后开始可以达到目的。

一些通过NSTextAttachmentUIImage转换为NSAttributedString的代码:How to add images as text attachment in Swift using nsattributedstring

关于ios - Swift:加载样式 RTF 后将字符串替换为 UITextView 中的 NSTextAttachment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47379391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com