有人可以帮我用Swift 2将rtf文本加载到UITextView中吗?我得到的答案已经过时了。该文本是关于如何玩我正在应用程序中编写的游戏的说明。到目前为止,我所能做的就是将所有rtf文本复制并粘贴到占位符框中。这适用于模拟器中的iPhone,但是当我在iPad模拟器或iPhone 6 Plus中尝试时,出现这种情况时会出现双垂直滚动条。它看起来很乱。
我现在也有一个相同文件的真实纯文本,所以我们也可以尝试。
斯威夫特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和5
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)")
}
}
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
}
您可以在Swift 2中使用以下代码读取rtf文件。
加载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
Swift 3代码:
if let rtfPath = Bundle.main.url(forResource: "description_ar", withExtension: "rtf") {
do {
let attributedStringWithRtf:NSAttributedString = try NSAttributedString(url: rtfPath, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil)
self.textView.attributedText = attributedStringWithRtf
} catch {
print("We got an error \(error)") //or handle how you want
}
}
受@MikeG启发的编辑和更新 10月21日更新的灵感来自@ RAJAMOHAN-S和@biomiker