使用 Swift 4 和 Xcode 使用捆绑包中 RTF 文件中的数据加载文本视图

All*_*all 0 rtf ios swift

我当前正在读取文本文件并将该信息加载到文本视图中。我有 100 多个项目,每个项目都有相当多的文本,因此这种方法效果很好。

我的问题是,我想将一些文本设为粗体,但无法使用标准文本文件来做到这一点,所以我想知道如何修改我当前拥有的代码,以便它加载 RTF 文件而不是文本文件的内容,当然在文本视图中正确显示。

let myString = String(indexNumber)
let detailFile = "detail" + myString
if let filepath = Bundle.main.path(forResource: detailFile, ofType: "txt") {
    do {
        let contents = try String(contentsOfFile: filepath)
        detailsTextView.text = contents
    } catch {
        detailsTextView.text = detailFile + " contents could not be loaded"
    }
} else {
    detailsTextView.text = detailFile + " detail file could not be found"
}
Run Code Online (Sandbox Code Playgroud)

mat*_*att 5

我自己的测试代码示例(RTF 文件名为“test.rtf”,self.tv是文本视图):

let url = Bundle.main.url(forResource: "test", withExtension: "rtf")!
let opts : [NSAttributedString.DocumentReadingOptionKey : Any] =
    [.documentType : NSAttributedString.DocumentType.rtf]
var d : NSDictionary? = nil
let s = try! NSAttributedString(url: url, options: opts, documentAttributes: &d)
self.tv.attributedText = s
Run Code Online (Sandbox Code Playgroud)