2016-02-29 13 views
3

有人可以幫助我用Swift 2加載一個RTF文本到UITextView中嗎?我得到的答案已過時,並且已過時。該文本是關於如何玩我在應用程序中編寫的遊戲的說明。到目前爲止,我所能做的就是將所有rtf文本複製並粘貼到佔位符框中。這適用於模擬器中的iPhone,但在iPad模擬器或iPhone 6 Plus中嘗試時,出現雙垂直滾動條時,我會這樣做。它看起來很混亂。在Swift 2中加載rtf文件到UITextView中

我現在也有相同文件的真實純文本,所以我們也可以嘗試。

回答

1
if let rtfPath = NSBundle.mainBundle().URLForResource("description_ar", withExtension: "rtf") 
{ 
    let attributedStringWithRtf = NSAttributedString(fileURL: rtfPath, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil, error: nil) 
    self.textView.attributedText = attributedStringWithRtf 
} 
+0

我已經試過這個代碼和編譯器告訴我,它不能調用初始化爲NSAttributedString所提供的參數列表。我錯過了什麼? –

1

可以讀取RTF文件,使用下面的代碼在斯威夫特2

加載RTF文件

let path = NSBundle.mainBundle().pathForResource("sample-rtf", ofType: "rtf") 

    let contents: NSString 
    do { 
     contents = try NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding) 
    } catch _ { 
     contents = "" 
    } 

    let array : NSArray = contents.componentsSeparatedByString("\n"); 

    self.textView.text = (array.objectAtIndex(0) as! String); 

    //self.textView.text = contents as String 

嘗試使用純文本(TXT)文件,而不是RTF。 RTF文件也包含關於文本的格式化信息。這就是你閱讀內容後看到的不必要的東西。

在Mac TextEdit中打開rtf文件並按下Cmd + Shift + T(這會將其轉換爲純文本並刪除所有格式),然後另存爲txt。

加載文本文件

let path = NSBundle.mainBundle().pathForResource("sample-text", ofType: "txt") 

    let contents: NSString 
    do { 
     contents = try NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding) 
    } catch _ { 
     contents = "" 
    } 

    self.textView.text = contents as String 
+0

我添加了上面的代碼,但仍然收到錯誤消息。 –

+0

我在執行「預期聲明」的do-catch代碼中收到錯誤,而且我必須將代碼編寫爲「let contents:NSString =」「',因爲如果我沒有這樣做,編譯器會說這個類沒有初始化程序。到目前爲止,我不能測試代碼,因爲它不會編譯,如果我初始化內容變量,上面的錯誤出現 –

+0

我已經做了調整,把路徑常量在@IBOutlet聲明下,其餘的在ViewDidLoad( )函數,並取得了進展,但現在編譯器告訴我,它發現了一個零,同時解開一個可選的,一個致命的錯誤。爲什麼? –

0

斯威夫特3代碼:

編輯和@MikeG
啓發更新10月21日更新通過@啓發RAJAMOHAN-S和@biomiker

+1

這應該是接受的答案 – Alexey

+0

這是不正確的斯威夫特3代碼,看我發佈的回答 – MikeG

+0

我更新了我的代碼是斯威夫特3兼容... – Chucky

12

斯威夫特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)") 
      } 
     } 

斯威夫特4更新

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)") 
     } 
    } 
+1

謝謝!適用於「html」文件以及.DocumentType.html – ursa

相關問題