Skip to content

Instantly share code, notes, and snippets.

@JoeFerrucci
Created May 20, 2016 17:04
Show Gist options
  • Save JoeFerrucci/9fe6e5b1717ae577ad92001ccd3a450b to your computer and use it in GitHub Desktop.
Save JoeFerrucci/9fe6e5b1717ae577ad92001ccd3a450b to your computer and use it in GitHub Desktop.
CopyableLabel - a typical UILabel with "Copy" functionality.
import UIKit
class CopyableLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
userInteractionEnabled = true
addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(CopyableLabel.showMenu(_:))))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func showMenu(sender: AnyObject?) {
becomeFirstResponder()
let menuController = UIMenuController.sharedMenuController()
if !menuController.menuVisible {
menuController.setTargetRect(bounds, inView: self)
menuController.setMenuVisible(true, animated: true)
}
}
override func copy(sender: AnyObject?) {
let pasteBoard = UIPasteboard.generalPasteboard()
pasteBoard.string = text
let menuController = UIMenuController.sharedMenuController()
menuController.setMenuVisible(false, animated: true)
}
override func canBecomeFirstResponder() -> Bool {
return true
}
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
return action == #selector(NSObject.copy(_:))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment