在項目中需要添加 3D Touch 功能, 雖然之前做過,但是一些細節的設置忘了??,所以就寫下來吧,權當作自己的復習
需要明白
- UITouch 里有一個 force 屬性,它代表的是按壓的力度
- UIViewController 的 peek 為開始按壓作用的視圖的動作, pop :在peek的基礎上繼續按壓
- UIApplicationShortcutItem 可以在按壓應用的圖標處添加一些快捷操作
Peek & Pop
1. 注冊使用
// MARK: - Register for 3D touch
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
switch traitCollection.forceTouchCapability {
case .available:
print("available")
registerForPreviewing(with: self, sourceView: tableView)
case .unavailable:
print("unavailable")
case .unknown:
print("unknown")
}
}
( tableView 可以改為作用的視圖 )
2. 實現代理
// MARK: - Peek & Pop
extension ViewController: UIViewControllerPreviewingDelegate {
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
print("viewControllerForLocation")
guard let indexPath = tableView.indexPathForRow(at: location),
let cell = tableView.cellForRow(at: indexPath) else {
return nil
}
let identifier = "DetailViewController"
guard let detailVC = storyboard?.instantiateViewController(withIdentifier: identifier) as? DetailViewController else {
return nil
}
// for peek & pop
detailVC.item = TableItem.all[indexPath.row]
previewingContext.sourceRect = cell.frame
// for preview action
detailVC.fromViewController = self
return detailVC
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
print("viewControllerToCommit")
show(viewControllerToCommit, sender: self)
}
}
其中 previewingContext(_:viewControllerForLocation:) 方法是在 peek 的時候調用的,此時可以做一些賦值操作(比如數據傳遞等),然后根據方法文檔的提示需要設置一下 sourceRect ;
previewingContext(_:commitViewController:)方法是在 Pop 時調用的。
(需要注意的是在測試的時候發現
調用 previewingContext(:viewControllerForLocation:) 的時候 destination view controller 會調用一次 viewWillAppear & viewDidAppear了;
調用 previewingContext(:commitViewController:) 的時候 destination view controller 還會再次 調用一次 viewWillAppear & viewDidAppear)。
此時就能夠使用 Peek & Pop功能了!
3. 添加 Preview actions
// MARK: - Preview Action
override var previewActionItems: [UIPreviewActionItem] {
// default style
let show = UIPreviewAction(title: "Show", style: .default) { (action, viewController) in
guard let sourceVC = self.fromViewController,
let desVC = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as? DetailViewController else {
return
}
desVC.fromViewController = sourceVC
desVC.item = self.item
sourceVC.show(desVC, sender: nil)
}
// selected style
let check = UIPreviewAction(title: "selected", style: .selected) { (action, viewController) in
}
// delete style
let delete = UIPreviewAction(title: "Delete", style: .destructive) { (action, viewController) in
guard let sourceVC = self.fromViewController,
let item = self.item else { return }
TableItem.delete(item: item)
sourceVC.tableView.reloadData()
}
return [show, check, delete]
}
主要是在 destination view controller 里設置一些Action 的操作(類似于UIAlertController)
此時 Peek 的時候再向上滑動就可以看到相應的Action 了!
按壓應用圖標
app 的按壓 shortcuts 共有兩種類型:
- Static shortcuts, 直接在 Info.plist 里面配置,安裝應用的時候就可以直接使用了
- Dynamic shortcuts,在 runtime 的時候配置,可以添加,刪除。只有執行相關操作的時候才會在按壓應用圖標的時候顯示
添加 static shortcut
代碼配置如下
<key>UIApplicationShortcutItems</key>
<array>
<dict>
<key>UIApplicationShortcutItemTitle</key>
<string>Add</string>
<key>UIApplicationShortcutItemType</key>
<string>com.ju.demo.add</string>
<key>UIApplicationShortcutItemIconType</key>
<string>UIApplicationShortcutIconTypeAdd</string>
</dict>
</array>
可以在里面配置【類型,主標題,副標題,圖片等】
在 AppDelegate.swift實現相關操作
// MARK: - Home screen shortcuts
extension AppDelegate {
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
handleShortcutItem(shortcutItem: shortcutItem)
completionHandler(true)
}
private func handleShortcutItem(shortcutItem: UIApplicationShortcutItem) {
switch shortcutItem.type {
case "com.ju.demo.add": // static
addNewOne()
case "com.ju.demo.share": // dynamic
share()
default:
break
}
}
// static method
private func addNewOne() {
if let newvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NewViewController") as? NewViewController,
let rootVC = window?.rootViewController?.targetViewController as? ViewController {
newvc.delegate = rootVC
let navc = UINavigationController(rootViewController: newvc)
rootVC.present(navc, animated: true, completion: nil)
}
}
// dynamic method
private func share() {
if let item = TableItem.all.first,
let detailVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DetailViewController") as? DetailViewController,
let rootVC = window?.rootViewController?.targetViewController as? ViewController {
detailVC.item = item
detailVC.share = true
rootVC.show(detailVC, sender: nil)
}
}
}
現在按壓應用圖標就可以使用 Static shortcuts 了
添加 dynamic shortcut
添加類似下面的方法
static func configureDynamicShortcuts() {
if all.count > 0 {
let shortcutType = "com.ju.demo.share"
let shortcutItem = UIApplicationShortcutItem(type: shortcutType,
localizedTitle: "Share",
localizedSubtitle: "share content",
icon: UIApplicationShortcutIcon(type: .share),
userInfo: nil)
UIApplication.shared.shortcutItems = [shortcutItem]
} else {
UIApplication.shared.shortcutItems = []
}
}
方法做的是判斷是否滿足出現對應的 dynamic shortcut,滿足條件顯示,否則不顯示
現在 Static shortcuts & Dynamic shortcuts 都實現了