Created
February 28, 2019 06:53
-
-
Save baryon/bd2d3e7fe1fa57d19dae1d88f7662c32 to your computer and use it in GitHub Desktop.
CopyableLabel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Original Source: | |
// https://stackoverflow.com/questions/1246198/show-iphone-cut-copy-paste-menu-on-uilabel | |
class CopyableLabel: UILabel { | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
self.sharedInit() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
self.sharedInit() | |
} | |
func sharedInit() { | |
self.isUserInteractionEnabled = true | |
self.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(self.showMenu))) | |
} | |
@objc func showMenu(_ recognizer: UILongPressGestureRecognizer) { | |
self.becomeFirstResponder() | |
let menu = UIMenuController.shared | |
let locationOfTouchInLabel = recognizer.location(in: self) | |
if !menu.isMenuVisible { | |
var rect = bounds | |
rect.origin = locationOfTouchInLabel | |
rect.size = CGSize(width: 1, height: 1) | |
menu.setTargetRect(rect, in: self) | |
menu.setMenuVisible(true, animated: true) | |
} | |
} | |
override func copy(_ sender: Any?) { | |
let board = UIPasteboard.general | |
board.string = text | |
let menu = UIMenuController.shared | |
menu.setMenuVisible(false, animated: true) | |
} | |
override var canBecomeFirstResponder: Bool { | |
return true | |
} | |
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { | |
return action == #selector(UIResponderStandardEditActions.copy) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment