您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

UIDocumentInteractionController 的使用:預覽、選單與委派

編輯:iOS 開發綜合

iOS 提供了讓 App 呼叫其他應用來預覽檔案的能力,這就是 Document Interaction。此外 iOS 也支援檔案關聯:讓其他程式透過你的 App 來開啟某種格式的檔案。而從 iOS 4.2 起,Quick Look Framework 更內建了多種文件格式的列印支援。相關的官方文件可參考 Document Interaction Controller 類別參考、Quick Look Framework 指南,以及 DocInteraction 範例程式。

一、建立實例

UIDocumentInteractionController 用靜態方法 interactionControllerWithURL: 建立,參數是一個指向本機檔案的 NSURL。

NSURL *url = [NSURL fileURLWithPath:path];
controller = [UIDocumentInteractionController interactionControllerWithURL:url];

注意:這個類別沒有公開的 init 方法,一定要走 interactionControllerWithURL:。另外,該 controller 與 UIPopoverPresentationController 一樣,並不會 retain 自己,因此必須由你持有強參考(實例變數或 property),否則在 present 之前就可能被回收,導致什麼都不顯示。

二、顯示預覽視窗

呼叫 presentPreviewAnimated: 會彈出全螢幕的 Quick Look 預覽,使用者可用手勢縮放、翻頁、旋轉。

BOOL b = [controller presentPreviewAnimated:YES];

三、顯示操作選單

若不希望直接跳出預覽,而是先讓使用者選擇要做什麼,可以顯示一個選項選單。這組方法只有顯示位置的差異:

- presentOptionsMenuFromRect:inView:animated:
- presentOptionsMenuFromBarButtonItem:animated:
- presentOpenInMenuFromRect:inView:animated:
- presentOpenInMenuFromBarButtonItem:animated:

Options 選單包含預覽、列印、分享等全部可用動作;OpenIn 選單則只列出「用其他應用開啟」的項目。以 rect 版本為例:

CGRect navRect = self.navigationController.navigationBar.frame;
navRect.size = CGSizeMake(1500.0f, 40.0f);

[controller presentOptionsMenuFromRect:navRect inView:self.view animated:YES];

這裡有個實務技巧:把 rect 的寬度刻意設得比螢幕還寬(如 1500),可以讓選單從導覽列整體下方展開,視覺上更貼近 iOS 原生工具列選單的外觀。若在 iPad 上呈現,選單會變成 popover,記得實作 presentationControllerDidDismiss: 之類的回呼以釋放資源。

四、委派:告訴系統怎麼畫預覽

只要你打算顯示預覽,就必須設定 delegate。若沒有委派,controller 會不知道要在哪個檢控器、哪個區域中呈現內容。

controller.delegate = self;

委對物件需要實作一系列方法,最常見的三個會在使用者按下「快速查看」時依序被呼叫:

- (UIViewController*)documentInteractionControllerViewControllerForPreview:
        (UIDocumentInteractionController*)controller {
    return self;
}

- (UIView*)documentInteractionControllerViewForPreview:
        (UIDocumentInteractionController*)controller {
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:
        (UIDocumentInteractionController*)controller {
    return self.view.frame;
}

三者的分工是:檢控器決定預覽畫面由誰呈現、view 決定預覽內容畫在哪個視圖上、rect 決定預覽佔據該視圖的哪個矩形區域。

此外還有一個收尾回呼,用來在預覽關閉時釋放 controller:

// 使用者按下預覽視窗的「Done」時呼叫
- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController*)_controller {
    [_controller autorelease];
}

實務提醒

可以開啟哪些應用,取決於裝置上裝了什麼。willOpenMenu:withApplication: 與 documentInteractionController:canPerformAction: 這類方法回傳的資訊,反映的是當前環境的實際能力。若裝置上沒有能處理該格式的 App,選單可能只有預覽一項,這不是 bug。

UIDocumentInteractionController 並非 UIActivityViewController 的替代品。前者專注於「預覽與用其他 App 開啟本機檔案」,後者才是通用的分享/動作面板。兩者可以並用:先用前者預覽,需要分享時再跳出後者。

iOS 13 之後,若只是要預覽檔案,可以考慮 QuickLook 的 QLPreviewController。它同樣走 Quick Look,但委派設計更現代、支援多檔案與自訂來源,是目前的建議做法。UIDocumentInteractionController 仍可用於「開啟方式」選單這類需求。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved