您好,我想知道如何在UITextView中加载RTF或文本文件,我使用了几个代码但都没有成功。
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"txt"];
myTextView.text = filePath;
谢谢您。
你可以尝试这个:
NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
myTextView.text = myText;
myTextView.attributedText =
[ NSAttributedString.alloc
initWithFileURL:[ NSBundle.mainBundle URLForResource:@"filename" withExtension:@"rtf" ]
options:nil
documentAttributes:nil
error:nullptr
];
UITextView
的 attributedText
属性。 - Dalmazioalloc
最多是令人困惑的,最糟糕的情况下是滥用点语法。不遵循标准的多行参数对齐约定会使阅读变得困难。 - SwampThingTom你目前所做的可以得到文件名,但需要更进一步并实际读取文件内容到一个NSString中,可以使用类似以下的方法实现:
NSError *err = nil;
NSString *fileContents = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:&err];
if (fileContents == nil) {
NSLog("Error reading %@: %@", filePath, err);
} else {
myTextView.text = fileContents;
}
对于纯文本,这将起作用(假设您的文件采用UTF8编码); 对于RTF,您需要进行更高级的操作(UITextView不知道如何显示RTF)。
@property (unsafe_unretained) IBOutlet NSTextView *txtRich;
NSBundle *myBundle = [NSBundle mainBundle];
NSString *sFile= [myBundle pathForResource:@"myrichfile" ofType:@"rtfd"];
[self.txtRich readRTFDFromFile:sFile];
你可能想知道这个mainBundle
是从哪里来的,是否需要在某个地方声明它。答案是否定的。它是默认创建的魔法变量,就像NSNotificationCenter defaultCenter
变量一样。它指的是你自己的应用程序包。
这是如何加载rtf文件的方法
NSURL * url = [NSBundle.mainBundle URLForResource:@"example"
withExtension:@"rtf"];
NSData * content = [NSData dataWithContentsOfURL:url];
NSError * e;
NSAttributedString * aText = [[NSAttributedString alloc]
initWithData:content
options:@{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType}
documentAttributes:NULL
error:&e];
self.textView.attributedText = aText;