开发中遇到很多需要预览附件的情况,但是系统中的QLPreviewItem的previewItemTitle是【只读】的,也就是服务器传过来如果是123334323232.doc的文件的话那么标题就是123334323232,而不能显示中文名。这个就很恶心。
这里实现的办法是继承并重写QLPreviewItem,把previewItemTitle属性重写为可读可写的。
重写的QLPreviewItem代码:(代码搬运自国外论坛,请作者不要鄙视,我就是记录下自己以后忘记了查看下)
@interface BasicPreviewItem : NSObject <QLPreviewItem>{
}
@property (nonatomic, retain) NSURL * previewItemURL;
@property (nonatomic, copy) NSString* previewItemTitle;
@end
@implementation BasicPreviewItem
@synthesize previewItemURL, previewItemTitle;
-(void)dealloc
{
self.previewItemURL = nil;
self.previewItemTitle = nil;
}
@end
在代码调用的时候将原有的QLPreviewItemt替换为BasicPreviewItem,然后开开心心的给预览界面的title赋值。
下面留下个完整调用的代码吧!
#pragma mark 打开文件
-(void)openDocumentFile{
QLPreviewController * previewoCntroller = [[QLPreviewController alloc] init] ; previewoCntroller.navigationController.navigationBarHidden = NO; previewoCntroller.navigationItem.hidesBackButton = YES; previewoCntroller.dataSource = self; previewoCntroller.delegate = self; previewoCntroller.currentPreviewItemIndex = 0;
//设置下自行一返回按钮
UIButton * backBtn =[[UIButton alloc] initWithFrame:CGRectMake(106, 20, 32, 32)];
UIImageView *btnImage =[[UIImageView alloc] initWithFrame:CGRectMake(0, 8, 11, 17)]; btnImage.image = [UIImage imageNamed:@"backImage"];
[backBtn addSubview:btnImage];
[backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchDown];
backBtn.backgroundColor=[UIColor clearColor];
__weak typeof(self) weakSelf = self; UIBarButtonItem *homeButtonitem=[[UIBarButtonItem alloc] initWithCustomView:backBtn]; previewoCntroller.navigationItem.leftBarButtonItem = homeButtonitem; [weakSelf.navigationController pushViewController: previewoCntroller animated:YES];
}
#pragma mark ---QLPreviewControllerDelegate- start-
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller{ return 1;}
- (id)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index{
BasicPreviewItem * item = [[BasicPreviewItem alloc] init];
//将本地文件写进指定位置
NSFileManager *fileManager = [NSFileManager defaultManager];
//获取cache文件夹目录
NSArray * cachesPathArr = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString * cachesPath = cachesPathArr[0];
//获取本地完整的文件路径
NSString * fileName = [NSString stringWithFormat:@"%@/%@.%@",cachesPath,currentFileObject.fileUniqueName,currentFileObject.fileType];
if ([fileManager fileExistsAtPath:fileName]) {
NSData *audioData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:currentFileObject.fileUniqueName ofType:currentFileObject.fileType]];
[audioData writeToFile:fileName atomically:YES];
item.previewItemURL = [NSURL fileURLWithPath:fileName];
item.previewItemTitle = currentFileObject.fileName;
}else{
[AppPublic alertViewWithController:self andTitle:@"提示" andMessage:@"没有加载到对应文件!"];
}
return item;
}
#pragma mark ---QLPreviewControllerDelegate-End-