由于自己喜歡看段子,最近做了一個(gè)看段子的APP。主要是因?yàn)?strong>網(wǎng)易新聞和今日頭條分享段子的姿勢(shì)恕我不能忍。
完成后的效果
2017-02-21 16_00_55.gif
- 你只需要點(diǎn)擊你想要分享的段子
- 然后選擇QQ或者Wechat,跳轉(zhuǎn)后點(diǎn)擊粘貼就好了
不用像網(wǎng)易新聞和今日頭條分享一個(gè)鏈接,別人想看還得點(diǎn)進(jìn)去。當(dāng)然他們也可以復(fù)制,但是那姿勢(shì)真的不優(yōu)雅。
坑
在其中用到了UIMenuController
這個(gè)控件。真的是一個(gè)巨坑,上網(wǎng)搜了各種帖子,都不能解決我所遇到的問(wèn)題。最終這篇帖子幫了我。
1
UIMenuItem(title: "QQ", action: #selector(mqq))
看到這個(gè)結(jié)構(gòu),你很自然先到mqq這個(gè)方法接收傳遞的對(duì)象是UIMenuItem
但是他傳遞的是UIMenuController
2
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let cell = tableView.cellForRow(at: indexPath) {
// self.becomeFirstResponder() 這里先注釋
let qqItem = UIMenuItem(title: "QQ", action: #selector(mqq))
let wechatItem = UIMenuItem(title: "wechat", action: #selector(wechat))
let menuController = UIMenuController.shared
menuController.menuItems = [qqItem, wechatItem]
menuController.setTargetRect(cell.frame, in: cell.superview!)
menuController.setMenuVisible(true, animated: true)
selectedText = cell.textLabel?.text
}
}
這段代碼寫(xiě)在UITableViewController
中,在不切換tab的情況下,點(diǎn)擊cell后UIMenuController
是能顯示出來(lái)的,切換后就顯示不出來(lái)了。必須加上注釋的那句
3
func longPress(sender: UILongPressGestureRecognizer) {
if sender.state == .began {
self.becomeFirstResponder() // 這句很重要
let menuController = UIMenuController.shared
let item1 = UIMenuItem(title: "測(cè)試1", action: #selector(test1))
let item2 = UIMenuItem(title: "測(cè)試2", action: #selector(test2))
menuController.menuItems = [item1, item2]
menuController.setTargetRect(frame, in: superview!)
menuController.setMenuVisible(true, animated: true)
}
}
在上面的基礎(chǔ)上,把這段代碼放在自定義cell中,UIMenuController
又顯示不出來(lái)了
必須加上
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if [#selector(test1), #selector(test2)].contains(action) {
return true
}
return false
}
從方法名你可以看出就是可以執(zhí)行的方法,會(huì)顯示出對(duì)應(yīng)的UIMenuItem
如果你這樣
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return true
}
會(huì)顯示出系統(tǒng)內(nèi)置的和你定義的,如果你沒(méi)有實(shí)現(xiàn)對(duì)應(yīng)的Selector,會(huì)Crash
Screen Shot 2017-02-22 at 下午2.26.14.png
Screen Shot 2017-02-22 at 下午2.26.27.png
Screen Shot 2017-02-22 at 下午2.26.39.png
Screen Shot 2017-02-22 at 下午2.31.37.png
本文Demo