问题
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