O2CanCopyUILabel.swift 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. //
  2. // O2CanCopyUILabel.swift
  3. // O2Platform
  4. //
  5. // Created by FancyLou on 2020/8/26.
  6. // Copyright © 2020 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. // MARK: - 能够复制的UILabel
  10. class O2CanCopyUILabel: UILabel {
  11. override init(frame: CGRect) {
  12. super.init(frame: frame)
  13. setEvent()
  14. }
  15. required init?(coder: NSCoder) {
  16. super.init(coder: coder)
  17. }
  18. override func awakeFromNib() {
  19. super.awakeFromNib()
  20. addLongPressGesture()
  21. }
  22. //必须实现的两个方法
  23. override var canBecomeFirstResponder: Bool {
  24. return true
  25. }
  26. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  27. if action == #selector(copyText) {
  28. return true
  29. }
  30. return false
  31. }
  32. private func setEvent() {
  33. addLongPressGesture()
  34. NotificationCenter.default.addObserver(forName: UIMenuController.willHideMenuNotification, object: nil, queue: nil) { (note) in
  35. self.backgroundColor = UIColor.white
  36. }
  37. }
  38. private func addLongPressGesture() {
  39. self.isUserInteractionEnabled = true
  40. let longTap = UILongPressGestureRecognizer.init(target: self, action: #selector(longTapRecognizer))
  41. // 长按手势最小触发时间
  42. longTap.minimumPressDuration = 1.0
  43. // 长按手势需要的同时敲击触碰数(手指数)
  44. longTap.numberOfTouchesRequired = 1
  45. // 长按有效移动范围(从点击开始,长按移动的允许范围 单位 px
  46. // longTap.allowableMovement = 15
  47. self.addGestureRecognizer(longTap)
  48. }
  49. private func setMenuItems(){
  50. self.becomeFirstResponder()
  51. // 如果 Menu 已经被创建那就不再重复创建 menu
  52. if (UIMenuController.shared.isMenuVisible){
  53. return
  54. }
  55. let item1 = UIMenuItem.init(title: "复制", action: #selector(copyText))
  56. // 单例的形式获取menu
  57. let menu = UIMenuController.shared
  58. // 设置箭头方向
  59. menu.arrowDirection = .default
  60. // 设置 Menu 所显示的 items
  61. menu.menuItems = [item1]
  62. // 设置添加上 menu 的目标控件的 rect 和目标控件
  63. menu.setTargetRect(self.frame, in: self.superview!)
  64. // 令 Menu 可见
  65. menu.setMenuVisible(true, animated: true)
  66. }
  67. @objc private func longTapRecognizer(recognizer: UIGestureRecognizer) {
  68. if recognizer.state == .ended{
  69. self.backgroundColor = UIColor.white
  70. return
  71. }else if recognizer.state == .began{
  72. self.backgroundColor = UIColor.lightGray
  73. setMenuItems()
  74. }
  75. }
  76. @objc private func copyText() {
  77. let pboard = UIPasteboard.general
  78. pboard.string = self.text
  79. }
  80. }