Can somebody help me to load an rtf text into UITextView with Swift 2? The answers I've gotten are old and out of date. The text is instructions on how to play the game I'm writing in an app. So far, all I've been able to do is to copy and paste all the rtf text into the placeholder box. This works for iPhones in the simulator, but when trying it in the iPad simulator or iPhone 6 Plus there appears double vertical scroll bars when I do this. It looks messy.
I also now have a real plain text of the same file, so we can try that too.
Swift 3
if let rtfPath = Bundle.main.url(forResource: "SomeTextFile", withExtension: "rtf") {
do {
let attributedStringWithRtf:NSAttributedString = try NSAttributedString(url: rtfPath, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil)
self.textView.attributedText = attributedStringWithRtf
} catch let error {
print("Got an error \(error)")
}
}
Swift 4 & 5
if let rtfPath = Bundle.main.url(forResource: "someRTFFile", withExtension: "rtf") {
do {
let attributedStringWithRtf: NSAttributedString = try NSAttributedString(url: rtfPath, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
self.textView.attributedText = attributedStringWithRtf
} catch let error {
print("Got an error \(error)")
}
}
Swift 3 Code:
if let rtfPath = Bundle.main.url(forResource: "description_ar", withExtension: "rtf") {
do {
let attributedStringWithRtf:NSAttributedString = try NSAttributedString(url: rtfPath, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil)
self.textView.attributedText = attributedStringWithRtf
} catch {
print("We got an error \(error)") //or handle how you want
}
}
Edits and updates inspired by @MikeG
October 21 update inspired by @RAJAMOHAN-S and @biomiker
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With