Reputation: 6051
Hi i was wondering how should i load rtf or text file into UITextView i use several codes but did't work ,
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"txt"];
myTextView.text = filePath;
thank you .
Upvotes: 9
Views: 17339
Reputation: 767
This is how to load a rtf file
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;
Upvotes: 0
Reputation: 24886
@interface
line. Mine was @interface AppDelegate ()
. The reason for the three clicks is because by default when you drag a TextView control on a window, it creates 3 controls and it's only the inner, inner one that is set to NSTextView. The other controls deal with scrolling and screen clipping. Then, choose to create an outlet and name it something like txtRich
or whatever you want. This created this entry for me in my case:@property (unsafe_unretained) IBOutlet NSTextView *txtRich;
applicationDidFinishLaunching
. Inside that, paste something like this:NSBundle *myBundle = [NSBundle mainBundle];
NSString *sFile= [myBundle pathForResource:@"myrichfile" ofType:@"rtfd"];
[self.txtRich readRTFDFromFile:sFile];
You may be wondering where this mainBundle
comes from, and if you have to declare it somewhere. The answer is no. It's freaking magic, created by default, just like the NSNotificationCenter defaultCenter
variable. It refers to your own application bundle.
Upvotes: 0
Reputation: 5888
myTextView.attributedText =
[ NSAttributedString.alloc
initWithFileURL:[ NSBundle.mainBundle URLForResource:@"filename" withExtension:@"rtf" ]
options:nil
documentAttributes:nil
error:nullptr
];
Upvotes: 9
Reputation: 27900
What you've done so far will get you the name of the file, you need to go one step further and actually read the contents of the file into an NSString, using something like:
NSError *err = nil;
NSString *fileContents = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:&err];
if (fileContents == nil) {
NSLog("Error reading %@: %@", filePath, err);
} else {
myTextView.text = fileContents;
}
That will work for plain text (assuming your file is in UTF8 encoding); you'll have to do something a lot fancier for RTF (UITextView doesn't know how to display RTF).
Upvotes: 8
Reputation: 18741
You may try with this:
NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
myTextView.text = myText;
Upvotes: 15