Sapan Diwakar

Software developer

Follow me on Twitter Check out my code on GitHub View some of my designs on Dribbble Take a look at my Linked In profile

RTF Files and Attributed Strings

If you've ever tried setting up a UITextView in Storyboard, you might already know that it's an annoying task. The customizations don't work often and it's easy to mistakenly clear all styles with no way of coming back (unless of course you are using version control and don't have other changes in Storyboard that you don't mind reverting). Forget about localizing the strings or changing things in code.

Enter RTF. Rich Text Format (RTF) is a text formatting language devised by Microsoft Corporation. You can represent a character, paragraph, and document format attributes using plain text with interspersed RTF commands, groups, and escape sequences. The Application Kit’s extensions for NSAttributedString add support for reading and writing a number of popular document formats, including RTF.

The steps involved are very simple. Add an RTF file to the project (make sure that the file is also included in Copy Bundle Resources inside Build Phases). The following function converts an RTF file to NSAttributedString.

func loadRTF(from resource: String) -> NSAttributedString? {  
    guard let url = Bundle.main.url(forResource: resource, withExtension: "rtf") else { return nil }
    guard let data = try? Data(contentsOf: url) else { return nil }
    return try? NSAttributedString(data: data,
                                   options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType],
                                   documentAttributes: nil)

To load a file in text view, just use the following inside viewDidLoad

textView.attributedText = loadRTF(from: filename)  

This also allows you to handle localization automatically. All you need is to localize the file inside Xcode and include different versions for different languages and everything will be handled automatically. To localize the file, select the file in Xcode and click on Localize button on the File Inspector in the right menu. Then select the localizations you want for the file and you are done.