长按复制,粘贴,这个大多数情况会在文本控件中起作用,我们也可以通过UIMenuController 自定义一些需要的操作,这里,介绍一种通用的方法,添加自定义的“举报”行为。
//长按举报
class ReportLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(ReportLabel.showMenu(_:)))
self.addGestureRecognizer(longPress)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//需要重写以下两个方法
override func canBecomeFirstResponder() -> Bool {
return true
}
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
if action == #selector(CommentCell.report(_:)) {
return true
}
return false
}
//实现举报的方法
func report (sender: UIMenuController) {
}
//自定义UIMenuController
func showMenu(gestureRecognizer: UILongPressGestureRecognizer) {
self.becomeFirstResponder()
let touchPoint = gestureRecognizer.locationInView(self)
let touchArea = CGRect(origin: touchPoint, size: CGSize.zero)
let reportMenuItem = UIMenuItem(title: "举报", action: #selector(ReportLabel.report(_:)))
let customMenuController = UIMenuController.sharedMenuController()
customMenuController.menuItems = [reportMenuItem]
customMenuController.arrowDirection = .Default
customMenuController.setMenuVisible(true, animated: true)
customMenuController.setTargetRect(touchArea, inView: gestureRecognizer.view!)
customMenuController.update()
}
}
版权声明:本文为Scott_cc原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。