如何在 Ui 文本视图中以 swift 代码上传 RTF 文件

How to upload RTF file In Ui text view in swift code

如何在 UITextView 中加载 RTF 文件?

假设您在应用程序中包含一个名为 rtfdoc.rtf 的文件,这将使您入门:

let rtf = NSBundle.mainBundle().URLForResource("rtfdoc", withExtension: "rtf", subdirectory: nil, localization: nil)

let attributedString = NSAttributedString(fileURL: rtf, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil, error: nil)

let textView = UITextView(frame: CGRectMake(20,20,self.view.frame.size.width-40,self.view.frame.size.height-40))

textView.attributedText = attributedString

self.view.addSubview(textView)

编辑:故事板版本

要求的完整代码。这假设您已经连接了故事板的插座。

import UIKit
import Foundation

class ViewController: UIViewController {

    @IBOutlet var textView: UITextView!
    override func viewDidLoad() {
        super.viewDidLoad()
        if let rtf = NSBundle.mainBundle().URLForResource("rtfdoc", withExtension: "rtf", subdirectory: nil, localization: nil) {

            let attributedString = NSAttributedString(fileURL: rtf, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil, error: nil)
            textView.attributedText = attributedString
            textView.editable = false
        }


    }

}

注意:文本不可编辑,但仍可选择。

和iOS9上面的NSAttributed字符串会报错。您可以尝试使用以下代码:

do{
    let attrString =
    try NSMutableAttributedString(URL: rtfPath, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil)
                textView.attributedText = attrString 
}catch{}