簡體   English   中英

UITextView不顯示RTF文件中的格式化文本

[英]UITextView not showing formatted text from RTF File

我正在為iOS 9.1(使用Xcode 7.1和Swift 2.0)制作一個應用程序,其中包含一個UITextView用於顯示rtf資源文件中的格式化文本。 我在視圖控制器的viewDidLoad()函數中調用以下函數來加載文本:

func loadTutorialText() {
    if let rtfPath = NSBundle.mainBundle().URLForResource("TutorialText", withExtension: "rtf") {
        do {
            let attributedStringWithRtf = try NSAttributedString(URL: rtfPath, options: [NSDocumentTypeDocumentAttribute : NSRTFTextDocumentType], documentAttributes: nil)
            self.textView.attributedText = attributedStringWithRtf
        } catch {
            print("Error loading text")
        }
    }
}

當我運行該應用程序時,將加載rtf資源文件中的文本,但所有內容均顯示為純文本。 這是我正在使用的測試rtf文件的示例:

標題示例

文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本。

標題示例

文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本。

項目符號列表

  • 項目1
  • 項目2
  • 項目3

我需要為UITextView設置一些屬性以使其正確顯示嗎?

與其將documentAttributes設置為nil ,不如將它們讀入一個變量:

var d : NSDictionary? = nil
let attributedStringWithRtf = try NSAttributedString(
    URL: rtfPath, 
    options: [NSDocumentTypeDocumentAttribute : NSRTFTextDocumentType], 
    documentAttributes: &d)

編輯您的RTF文件在我的機器上可以正常工作:

在此處輸入圖片說明

從字面上看,該應用程序中唯一的代碼是:

class ViewController: UIViewController {
    @IBOutlet weak var tv: UITextView!
    override func viewDidLoad() {
        super.viewDidLoad()
        let rtfPath = NSBundle.mainBundle().URLForResource("TutorialText", withExtension: "rtf")!
        var d : NSDictionary? = nil
        let attributedStringWithRtf = try! NSAttributedString(
            URL: rtfPath,
            options: [NSDocumentTypeDocumentAttribute : NSRTFTextDocumentType],
            documentAttributes: &d)
        self.tv.attributedText = attributedStringWithRtf
    }
}

我要建議的是,如果這不是您所看到的,那么您還有其他代碼沒有告訴我們這正在發生並弄亂了一切。

刪除“接口”構建器中添加到Font屬性中的另一個Size類的所有字體大小設置,原因將消除。

SWIFT 4

[NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType]

不要為我迅速工作4

這是我的解決方案:

let attributedStringWithRtf:NSAttributedString = try NSAttributedString(
                    url: rtfPath,
                    options: [.documentType: NSAttributedString.DocumentType.rtf],
                    documentAttributes: nil
                )
                self.textView.attributedText = attributedStringWithRtf

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM