Swift中3DTouch的简单使用

1.应用外3DTouch功能

就是给应用的桌面图标施加压力产生菜单功能,极大的提高应用使用的便捷性,更加快速定位到常用功能,类似微信这样:

Swift中3DTouch的简单使用_第1张图片
WechatIMG1.jpeg
info.plist创建3DTouch
Swift中3DTouch的简单使用_第2张图片
image.png
UIApplicationShortcutItems:数组中的元素就是我们的那些快捷选项标签。
UIApplicationShortcutItemTitle:标签标题(必填)
UIApplicationShortcutItemType:标签的唯一标识 (必填)
UIApplicationShortcutItemIconType:使用系统图标的类型,如搜索、定位、home等(可选)
UIApplicationShortcutItemIcon File:使用项目中的图片作为标签图标 (可选)
UIApplicationShortcutItemSubtitle:标签副标题 (可选)
UIApplicationShortcutItemUserInfo:字典信息,如传值使用 (可选)
代码创建3DTouch

在APPDelegate里面程序启动方法里,首先判断当前设备是否支持3DTouch功能,如果支持就创建。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        window = UIWindow(frame: UIScreen.main.bounds)
        
        let nav = UINavigationController(rootViewController: ViewController())
        
        window?.rootViewController = nav
        
        window?.makeKeyAndVisible()
        
        if window?.traitCollection.forceTouchCapability == UIForceTouchCapability.available {
            init3DTouchItem()
        }
        
        return true
    }

然后,根据type判断点击的某个item事件

extension AppDelegate {
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        let urlStr = url.absoluteString
        if urlStr.hasPrefix("widgettest") {
            let range = (urlStr as NSString).range(of: "id=")
            let id = (urlStr as NSString).substring(from: range.location + 3)
            print("id====== \(id)")
            return true
        }
        return false
    }
    
    func init3DTouchItem() {
        let icon1 = UIApplicationShortcutIcon(type: UIApplicationShortcutIcon.IconType.search)
        let item1 = UIApplicationShortcutItem(type: "type1", localizedTitle: "标题一", localizedSubtitle: "副标题一", icon: icon1, userInfo: nil)
        
        let icon2 = UIApplicationShortcutIcon(type: UIApplicationShortcutIcon.IconType.search)
        let item2 = UIApplicationShortcutItem(type: "type2", localizedTitle: "标题二", localizedSubtitle: "副标题二", icon: icon2, userInfo: nil)
        
        UIApplication.shared.shortcutItems = [item1, item2]
    }
    
    func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
        if shortcutItem.type == "type1" {
            
        } else if shortcutItem.type == "type2" {
            
        } else {
            
        }
    }
}

3. 上线后 系统会自动添加分享功能

你可能感兴趣的:(Swift中3DTouch的简单使用)