Load Text View with data from RTF file in bundle using Swift 4 and Xcode

|▌冷眼眸甩不掉的悲伤 提交于 2020-04-12 07:26:26

问题


I am currently reading text files and loading that information into a text view. I have over 100 items and quite a bit of text per item so this method works well.

My problem is that I would like to make some text bold and can not do that using a standard text file so I am wondering how I can modify the code I currently have so that it loads the contents of a RTF file instead of the text file, and of course displays correctly in the text view.

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"
}

回答1:


Example from my own test code (the RTF file is called "test.rtf", self.tv is the text view):

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


来源:https://stackoverflow.com/questions/49618118/load-text-view-with-data-from-rtf-file-in-bundle-using-swift-4-and-xcode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!