Allan Hall
Allan Hall

Reputation: 33

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

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

Upvotes: 0

Views: 1717

Answers (1)

matt
matt

Reputation: 535121

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

Upvotes: 5

Related Questions