iOS 使用使用UIDocumentInteractionController预览文件(支持PDF、word、Excel、图片等)
[toc]
前言
应公司需求,在项目中需要加入文件预览功能,网上搜说了一下,发现苹果iOS本身有自己的文件预览的API,那就简单多了。
查看APi之后,我们发现UIDocumentInteractionController是个很特别的控制器,它不是继承UIViewController的,而是直接继承NSobject的。还有通过查看它的属性和代理方法,提供一个菜单提供一个菜单,允许用户快速查看、打开或复制文件指定的项目,自动确定正确的应用程序或应用程序,原文如下:
// Presents a menu allowing the user to Quick Look, open, or copy the item specified by URL.
// This automatically determines the correct application or applications that can open the item at URL.
// Returns NO if the options menu contained no options and was not opened.
// Note that you must implement the delegate method documentInteractionControllerViewControllerForPreview: to get the Quick Look menu item.
下面是实现代码:
#import "ViewController.h"
@interface ViewController ()<UIDocumentInteractionControllerDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title=@"预览";
NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"iOS开发指南.pdf" ofType:nil];
NSURL *url = [NSURL fileURLWithPath:urlStr];
UIDocumentInteractionController *documentVc = [UIDocumentInteractionController interactionControllerWithURL:url];
documentVc.delegate = self;
[documentVc presentPreviewAnimated:YES];
}
#pragma mark - UIDocumentInteractionController 代理方法
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
return self;
}
- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller{
return self.view;
}
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller{
return self.view.bounds;
}
这三个代理的使用告诉DocumentInteraction Controller如何显示。显示在哪里,和显示的大小
documentInteractionControllerViewControllerForPreview回调控制器
documentInteractionControllerViewForPreview回调View
documentInteractionControllerRectForPreview视图