Skip to content

Instantly share code, notes, and snippets.

@kylerohr
Created April 18, 2015 16:07
Show Gist options
  • Save kylerohr/d377bd31e6ffad6b0bd2 to your computer and use it in GitHub Desktop.
Save kylerohr/d377bd31e6ffad6b0bd2 to your computer and use it in GitHub Desktop.
Long Press Copyable UILabel
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Create our textLabel
let textLabel = MagicLabel(frame: CGRect(x: 50.0, y: 50.0, width: 200.0, height: 30.0))
self.view.addSubview(textLabel)
textLabel.text = "1234567890"
// Allow user interaction with the label
textLabel.userInteractionEnabled = true
// Add the gesture recognizer
let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: "handleLongPress:")
textLabel.addGestureRecognizer(gestureRecognizer)
}
func handleLongPress(recognizer: UIGestureRecognizer) {
if let view = recognizer.view, let superview = recognizer.view?.superview {
// First, let the label/view becomeFirstResponder
view.becomeFirstResponder()
// Next, grab the sharedMenuController and create a Copy item
let menuController = UIMenuController.sharedMenuController()
let copyItem = UIMenuItem(title: "Copy", action: "copyAction:")
menuController.menuItems = [copyItem]
menuController.setTargetRect(view.frame, inView: superview)
// Finally, show the menu
menuController.setMenuVisible(true, animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
/**
Our custom MagicLabel class which allows copying
*/
class MagicLabel: UILabel {
override func canBecomeFirstResponder() -> Bool {
return true
}
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
return action == "copyAction:"
}
func copyAction(sender: AnyObject) {
UIPasteboard.generalPasteboard().setValue(self.text ?? "", forPasteboardType: "public.utf8-plain-text")
}
}
@shuvo1997
Copy link

nice & clean code with good explanation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment