iOS 3D Touch

在項(xiàng)目中需要添加 3D Touch 功能谢肾, 雖然之前做過(guò),但是一些細(xì)節(jié)的設(shè)置忘了??冕杠,所以就寫下來(lái)吧,權(quán)當(dāng)作自己的復(fù)習(xí)

需要明白

  • UITouch 里有一個(gè) force 屬性分预,它代表的是按壓的力度
  • UIViewController 的 peek 為開始按壓作用的視圖的動(dòng)作, pop :在peek的基礎(chǔ)上繼續(xù)按壓
  • UIApplicationShortcutItem 可以在按壓應(yīng)用的圖標(biāo)處添加一些快捷操作

Peek & Pop

1. 注冊(cè)使用

    // 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. 實(shí)現(xiàn)代理

// 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 的時(shí)候調(diào)用的魁淳,此時(shí)可以做一些賦值操作(比如數(shù)據(jù)傳遞等)飘诗,然后根據(jù)方法文檔的提示需要設(shè)置一下 sourceRect 界逛;

previewingContext(_:commitViewController:)方法是在 Pop 時(shí)調(diào)用的。

(需要注意的是在測(cè)試的時(shí)候發(fā)現(xiàn)
調(diào)用 previewingContext(:viewControllerForLocation:) 的時(shí)候 destination view controller 會(huì)調(diào)用一次 viewWillAppear & viewDidAppear了息拜;
調(diào)用 previewingContext(
:commitViewController:) 的時(shí)候 destination view controller 還會(huì)再次 調(diào)用一次 viewWillAppear & viewDidAppear)净响。

此時(shí)就能夠使用 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 里設(shè)置一些Action 的操作(類似于UIAlertController)

此時(shí) Peek 的時(shí)候再向上滑動(dòng)就可以看到相應(yīng)的Action 了!

按壓應(yīng)用圖標(biāo)

app 的按壓 shortcuts 共有兩種類型:

  • Static shortcuts, 直接在 Info.plist 里面配置畏陕,安裝應(yīng)用的時(shí)候就可以直接使用了
  • Dynamic shortcuts,在 runtime 的時(shí)候配置犹芹,可以添加鞠绰,刪除。只有執(zhí)行相關(guān)操作的時(shí)候才會(huì)在按壓應(yīng)用圖標(biāo)的時(shí)候顯示
添加 static shortcut
屏幕快照 2017-09-06 下午5.57.02.png

代碼配置如下

    <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>

可以在里面配置【類型屿笼,主標(biāo)題翁巍,副標(biāo)題,圖片等】

AppDelegate.swift實(shí)現(xiàn)相關(guān)操作

// 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)
        }
    }
    
}

現(xiàn)在按壓應(yīng)用圖標(biāo)就可以使用 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 = []
        }
    }

方法做的是判斷是否滿足出現(xiàn)對(duì)應(yīng)的 dynamic shortcut,滿足條件顯示例朱,否則不顯示

現(xiàn)在 Static shortcuts & Dynamic shortcuts 都實(shí)現(xiàn)了

Demo地址

Apple 3D Touch 文檔

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末洒嗤,一起剝皮案震驚了整個(gè)濱河市箫荡,隨后出現(xiàn)的幾起案子渔隶,更是在濱河造成了極大的恐慌,老刑警劉巖绞灼,帶你破解...
    沈念sama閱讀 218,386評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件呈野,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡军掂,警方通過(guò)查閱死者的電腦和手機(jī)轮蜕,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門蝗锥,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)跃洛,“玉大人,你說(shuō)我怎么就攤上這事终议∷翱危” “怎么了痊剖?”我有些...
    開封第一講書人閱讀 164,704評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵韩玩,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我陆馁,道長(zhǎng),這世上最難降的妖魔是什么叮贩? 我笑而不...
    開封第一講書人閱讀 58,702評(píng)論 1 294
  • 正文 為了忘掉前任击狮,我火速辦了婚禮,結(jié)果婚禮上益老,老公的妹妹穿的比我還像新娘彪蓬。我一直安慰自己,他們只是感情好档冬,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,716評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著酷誓,像睡著了一般态坦。 火紅的嫁衣襯著肌膚如雪盐数。 梳的紋絲不亂的頭發(fā)上玫氢,一...
    開封第一講書人閱讀 51,573評(píng)論 1 305
  • 那天谜诫,我揣著相機(jī)與錄音漾峡,去河邊找鬼猜绣。 笑死掰邢,一個(gè)胖子當(dāng)著我的面吹牛牺陶,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播辣之,決...
    沈念sama閱讀 40,314評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼掰伸,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了怀估?” 一聲冷哼從身側(cè)響起狮鸭,我...
    開封第一講書人閱讀 39,230評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎多搀,沒(méi)想到半個(gè)月后歧蕉,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,680評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡康铭,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,873評(píng)論 3 336
  • 正文 我和宋清朗相戀三年惯退,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片从藤。...
    茶點(diǎn)故事閱讀 39,991評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡催跪,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出夷野,到底是詐尸還是另有隱情懊蒸,我是刑警寧澤,帶...
    沈念sama閱讀 35,706評(píng)論 5 346
  • 正文 年R本政府宣布悯搔,位于F島的核電站骑丸,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏妒貌。R本人自食惡果不足惜者娱,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,329評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望苏揣。 院中可真熱鬧黄鳍,春花似錦、人聲如沸平匈。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,910評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)增炭。三九已至忍燥,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間隙姿,已是汗流浹背梅垄。 一陣腳步聲響...
    開封第一講書人閱讀 33,038評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留输玷,地道東北人队丝。 一個(gè)月前我還...
    沈念sama閱讀 48,158評(píng)論 3 370
  • 正文 我出身青樓靡馁,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親机久。 傳聞我的和親對(duì)象是個(gè)殘疾皇子臭墨,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,941評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容