下面的代码打开一个文件打开对话框,使用户可以浏览并选择一个文件。如何将文件中的文本输出到Xcode中的故事板中的文本视图框中,而不是在输出框中显示?
-(IBAction)openButton:(id)sender {
// Create the File Open Dialog class.
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
// Enable the selection of files in the dialog.
[openDlg setCanChooseFiles:YES];
// Multiple files not allowed
[openDlg setAllowsMultipleSelection:NO];
// Can't select a directory
[openDlg setCanChooseDirectories:YES];
// Display the dialog. If the OK button was pressed,
// process the files.
if ( [openDlg runModal] == NSModalResponseOK )
{
// Once a file has been opened and assigned a file handle, the contents of that file may be read from the current offset position. The readDataOfLength method reads a specified number of bytes of data from the file starting at the current offset. For example, the following code reads 5 bytes of data from offset 10 in a file. The data read is returned encapsulated in an NSData object.
NSFileHandle *file;
NSData *databuffer;
NSURL *selection = openDlg.URLs[0];
NSString *path = [[selection path]stringByResolvingSymlinksInPath];
file = [NSFileHandle fileHandleForReadingAtPath:(@"%@", path)];
if (file == nil)
NSLog(@"Failed to open file");
databuffer = [file readDataToEndOfFile];
[file closeFile];
NSString* newStr = [NSString stringWithUTF8String:[databuffer bytes]];
NSLog(@"%@", newStr);
}
}
这里是代码的IBOutlet部分
@property (noatomic, readwrite, weak) IBOutlet NSTextField *sourceLabel;
-(IBAction) openButton:(id)sender;
我不知道还有什么办法可以将插座连接到textview以显示文件中的文字