3D Touch開發全面教程之Peek and Pop - 預覽和彈出
了解3D Touch
在iPhone 6s和iPhone 6s Plus中Apple引入了3D Touch技術。3D Touch的觸控技術,被蘋果稱為新一代多點觸控技術。系統只能支持iOS9+,硬件是iPhone6S+。
iOS9提供了四類API
- Home Screen Quick Action : 對着Icon按壓,彈出快捷菜單
- Peek & Pop : 對着APP內容按壓,會彈出內容預覽和快捷菜單
- WebView Peek & Pop : 使用
SFSafariViewController打開的網頁內容自帶Peek & Pop 效果 - UITouch Force Properties : 檢測用戶按壓力度
檢測是否支持3D Touch:UIForceTouchCapability 是一個枚舉值,取值如下:
case unknown //3D Touch檢測失敗
case unavailable //3D Touch不可用
case available //3D Touch可用
在UIViewController中traitCollection屬性中,可以間接獲取到UIForceTouchCapability
if(self.traitCollection.forceTouchCapability == .available){
//TODO ...
}
代碼實現
- 顯示peek視圖
- peek視圖時手指上滑,喚出peek視圖快速選項
代碼實現 1 - 顯示peek視圖
首先要控制器中注冊代理
registerForPreviewingWithDelegate(self, sourceView: view)
然后實現代理UIViewControllerPreviewingDelegate 的方法func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController?
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
我們申明一個peek視圖的控制器,也就是正常情況下點擊UITableViewCell要跳轉到的控制器,設置控制器內容和peek視圖的大小,設置大小使用preferredContentSize 屬性,如果為0的話則系統自動配置最佳大小
guard let indexPath = tableView.indexPathForRow(at: location) , let cell = tableView.cellForRow(at: indexPath) else {
return nil
}
let detailVc = DetailViewController()
detailVc.preferredContentSize = CGSize(width: 0, height: 0)
previewingContext.sourceRect = cell.frame
detailVc.mTitle = cell.textLabel?.text
return detailVc
}
代碼實現 2 - peek視圖時手指上滑,喚出peek視圖快速選項
要實現這個操作,需要在peek視圖對應的控制器中重寫previewActionItems方法
比如我這里重寫后是這樣的:
override var previewActionItems: [UIPreviewActionItem] {
let a1 = UIPreviewAction(title: "在新標簽中打開", style: .default, handler: { (action, vc) in
print(action.title)
})
let a2 = UIPreviewAction(title: "加入閱讀列表", style: .selected, handler: { (action, vc) in
print(action.title)
})
let a31 = UIPreviewAction(title: "拷貝", style: .default, handler: { (action, vc) in
print(action.title)
})
let a32 = UIPreviewAction(title: "收藏", style: .default, handler: { (action, vc) in
print(action.title)
})
let a3 = UIPreviewActionGroup(title: "共享&更多...", style: .default, actions: [a31,a32])
return [a1,a2,a3]
}
Web view peek and pop API (HTML鏈接預覽功能)
除了tableViewCell可以實現peek and pop, 原生的safari瀏覽器中的超鏈接可以支持3D touch,出現超鏈接的預覽,使用方法和前文中提到的方法類似。
ios 9 中增加了一個新的瀏覽器控制器叫做 SFSafariViewController ,它可以在你的程序中直接嵌入 Safari瀏覽器,簡單的寫一段示例代碼:
import SafariServices
let sasfarVc = SFSafariViewController(url: URL(string:"https://www.baidu.com"), entersReaderIfAvailable: true)
self.navigationController ?.pushViewController(sasfarVc, animated: true)
這樣,我們就在app內嵌的Safari瀏覽器並且打開了baidu的頁面,並且使用3d touch超鏈接也會有預覽的效果了。
參考:
