CopyLabel.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. import Foundation
  21. import CocoaLumberjackSwift
  22. @objc class CopyLabel : UILabel {
  23. @objc public var textForCopying : String?
  24. override init(frame: CGRect) {
  25. super.init(frame: frame)
  26. attachTapHandler()
  27. }
  28. required init?(coder: NSCoder) {
  29. super.init(coder: coder)
  30. attachTapHandler()
  31. }
  32. func attachTapHandler() {
  33. isUserInteractionEnabled = true
  34. let recognizer = UITapGestureRecognizer(
  35. target: self,
  36. action: #selector(handleTap(_:)))
  37. addGestureRecognizer(recognizer)
  38. }
  39. @objc override func copy(_ sender: Any?) {
  40. if let textForCopying = textForCopying {
  41. UIPasteboard.general.string = textForCopying
  42. } else if let text = text {
  43. UIPasteboard.general.string = text
  44. }
  45. }
  46. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  47. return action == #selector(copy(_:))
  48. }
  49. @objc func handleTap(_ recognizer: UIGestureRecognizer?) {
  50. guard let superview = superview else {
  51. DDLogError("Could not handle tap because superview was nil")
  52. return
  53. }
  54. if !UIAccessibility.isVoiceOverRunning {
  55. becomeFirstResponder()
  56. let copyMenu = UIMenuController.shared
  57. copyMenu.setTargetRect(frame, in: superview)
  58. copyMenu.setMenuVisible(true, animated: true)
  59. }
  60. }
  61. override var canBecomeFirstResponder: Bool {
  62. return true
  63. }
  64. }