Mac OS X開發學習 -打開文件選擇器並獲取文件


代碼如下:

   NSOpenPanel *openPanel = [NSOpenPanel openPanel];
    [openPanel setPrompt: @"打開"];
    
    openPanel.allowedFileTypes = [NSArray arrayWithObjects: @"txt", @"doc", nil];
    openPanel.directoryURL = nil;
    
    [openPanel beginSheetModalForWindow:[self gainMainViewController] completionHandler:^(NSModalResponse returnCode) {
        
        if (returnCode == 1) {
            NSURL *fileUrl = [[openPanel URLs] objectAtIndex:0];
            // 獲取文件內容
            NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingFromURL:fileUrl error:nil];
            NSString *fileContext = [[NSString alloc] initWithData:fileHandle.readDataToEndOfFile encoding:NSUTF8StringEncoding];
            
            // 將 獲取的數據傳遞給 ViewController 的 TextView
            ViewController *mainViewController = (ViewController *)[self gainMainViewController].contentViewController;
            mainViewController.showCodeTextView.string = fileContext;
        }
    }];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM