使用Swift 4和Xcode加载带有RTF文件的数据的文本视图



我当前正在阅读文本文件并将该信息加载到文本视图中。我有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"
}

我自己的测试代码中的示例(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

最新更新