swift 支持长按复制功能的 label

通过以下代码你将实现支持长按可复制功能的 label ,大致效果如下图所示:


swift 支持长按复制功能的 label_第1张图片
copylabel.gif
 /// 带长按复制功能的 label

import UIKit

class CopyLabel: UILabel {
  //system method
  override func awakeFromNib() {
    super.awakeFromNib()
    self.addLongPressHandler()
  }
  override init(frame: CGRect) {
    super.init(frame: frame)
    self.addLongPressHandler()
  }
  override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
    if action == #selector(NSObject.copy(_:)) {
      return true
    }else{
      return false
    }
  }
  override func copy(sender: AnyObject?) {
    let pBoard = UIPasteboard.generalPasteboard()
    pBoard.string = self.text
  }
  override func canBecomeFirstResponder() -> Bool {
    return true
  }
  required init?(coder aDecoder: NSCoder) {
    //实现父类的该方法
    super.init(coder: aDecoder)
  }

  // MARK: - private method
  func addLongPressHandler() {
    //UILabel默认不接收事件,添加touch事件
    self.userInteractionEnabled = true
    let longPressGesture = UILongPressGestureRecognizer.init(target: self, action: #selector(longPressAction))
    self.addGestureRecognizer(longPressGesture)
  }
  func longPressAction() {
    self.becomeFirstResponder()
    let copyItem = UIMenuItem(title: "复制", action: #selector(NSObject.copy(_:)))
    let menu = UIMenuController.sharedMenuController()
    menu.menuItems = [copyItem]
    if menu.menuVisible {
      return
    }
    menu.setTargetRect(bounds, inView: self)
    menu.setMenuVisible(true, animated: true)
  }
}

期待你的评论建议O(∩_∩)O~

你可能感兴趣的:(swift 支持长按复制功能的 label)