LoginSignup
10
6

More than 5 years have passed since last update.

【Swift4】リッチテキストファイル(rtf)のテキストをUITextViewに表示する。

Posted at

リッチテキストファイル(*.rtf)のテキストをUITextViewに表示する方法です。

操作の流れは

  • rtfをメインバンドルに組み込む
  • rtfファイルからNSAttributeStringsを作成
  • UITextViewのattributedTextプロパティに代入

rtfをメインバンドルに組み込む

今回はTerms.rtfというファイルをアプリに組み込みます。

rtfファイルからNSAttributeStringsを作成

getTermAttributeStringというメソッドを作りました。
NSAttributeStringsを作成したいと思います。


enum FileError: Error {
    case notExitPath
    case faildRead
}

func getTermAttributeString() throws -> NSAttributedString {

        if let url =  Bundle.main.url(forResource: "Terms", withExtension: "rtf") {
            do {
                let terms = try Data(contentsOf: url)
                let attributeString = try NSAttributedString(data: terms, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
                return attributeString

            } catch let error {
                print("ファイルの読み込みに失敗しました: \(error.localizedDescription)")
                throw FileError.faildRead
            }
        } else {
            throw FileError.notExitPath
        }
    }

説明です。


if let url =  Bundle.main.url(forResource: "Terms", withExtension: "rtf")

Bundle.main.urlメソッドでメインバンドルのファイルのURLを取得します。


try NSAttributedString(data: terms, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)

NSAttributedStringのイニシャライズでoptions[NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf]を指定します。
こうすることでリッチテキストフォーマットでNSAttributedStringを作ることができます。

UITextViewのattributedTextプロパティに代入

作ったNSAttributedStringをattributedTextに代入します。

termsTextView.attributedText = try viewModel.getTermAttributeString()

以上です。

参考

10
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
6