这里有个坑就是如果重载NSObject的copy方法,就会导致弹出菜单永远有一个copy在第一位,如果不重载系统的copy,实现自己的方法就一切OK😄
import UIKit
class UICopyLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
attachTapHandler()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
attachTapHandler()
}
override func canBecomeFirstResponder() -> Bool {
return true
}
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
return action == #selector(UICopyLabel.myCopy(_:))
}
func myCopy(sender: AnyObject?) {
let pboard = UIPasteboard.generalPasteboard()
pboard.string = text
}
func attachTapHandler() {
userInteractionEnabled = true
let long = UILongPressGestureRecognizer(target: self, action: #selector(UICopyLabel.tapHandler(_:)))
addGestureRecognizer(long)
}
func tapHandler(recognizer: UIGestureRecognizer) {
becomeFirstResponder()
let link = UIMenuItem(title: "copy", action: #selector(UICopyLabel.myCopy(_:)))
let menuVC = UIMenuController.sharedMenuController()
menuVC.menuItems = [link]
menuVC.setTargetRect(frame, inView: superview!)
menuVC.setMenuVisible(true, animated: true)
}
}
网友评论