美文网首页
可复制内容的Label

可复制内容的Label

作者: anddygon | 来源:发表于2016-10-20 10:50 被阅读34次

    这里有个坑就是如果重载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)
        }
        
    }
    

    相关文章

      网友评论

          本文标题:可复制内容的Label

          本文链接:https://www.haomeiwen.com/subject/ljsfuttx.html