Created
May 20, 2016 17:04
-
-
Save JoeFerrucci/9fe6e5b1717ae577ad92001ccd3a450b to your computer and use it in GitHub Desktop.
CopyableLabel - a typical UILabel with "Copy" functionality.
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
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