CopyableLabel.swift
1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// CopyableLabel.swift
// SwiftWarplyFramework
//
// Created by Manos Chorianopoulos on 26/10/22.
//
import Foundation
import UIKit
class CopyableLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
sharedInit()
}
func sharedInit() {
isUserInteractionEnabled = true
addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(showMenu(sender:))))
}
@objc
func showMenu(sender: AnyObject?) {
becomeFirstResponder()
let menu = UIMenuController.shared
if !menu.isMenuVisible {
menu.setTargetRect(bounds, in: self)
menu.setMenuVisible(true, animated: true)
}
}
override var canBecomeFirstResponder: Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(UIResponderStandardEditActions.copy(_:)) {
return true
}
return false
}
override func copy(_ sender: Any?) {
let board = UIPasteboard.general
if var textToCopy = text {
if (textToCopy.contains(", ")) {
textToCopy = textToCopy.replacingOccurrences(of: ", ", with: "")
}
print(textToCopy)
board.string = textToCopy
}
// board.string = text
let menu = UIMenuController.shared
menu.setMenuVisible(false, animated: true)
}
}