今天用swift 3.0 写UIMenuController 遇到一个坑,分享给大家
(1)懒加载 UIMenuController
private lazy var menuController:UIMenuController = {
let menu = UIMenuController.shared
let deleteItem = UIMenuItem(title: "Delete", action: #selector(self.deleteLine))
let editItems = UIMenuItem(title: "Edit", action: #selector(self.editRow))
menu.menuItems = [deleteItem ,editItems]
menu.arrowDirection = .down
return menu
}()
(2)在storyboard中创建一个lable 并且在controller中添加事件
self.lable.isUserInteractionEnabled = true
let longprss : UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.labAction))
self.lable.addGestureRecognizer(longprss)
(3)触发方法中设置menu属性
menuController.setTargetRect(self.lable.bounds, in: self.lable)
menuController.setMenuVisible(true, animated: true)
(4)第一个重要的地方:是要重写canBecomeFirstResponder()
override var canBecomeFirstResponder : Bool {
return true
}
(5)第二个重要的地方:实现canPerformAction方法
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if(action == #selector(self.deleteLine) || action == #selector(self.editRow))
{
return true;
}
else
{
return false;
}
}
网友评论