user2636197 user2636197 - 1 year ago 145
iOS Question

Does UILabel have any value to make it selectable?


have any value that can be set in order to make it selectable?

I have a label that I want to be selectable, (long press and a copy btn shows up) kinda like in Safari.

Answer Source

Yes, you need to implement a UIMenuController from a long press gesture applied to your UILabel. There is an excellent article about this on NSHipster, but the gist of the article is the following.

Create a subclass of UILabel and implement the following methods:

override func canBecomeFirstResponder() -> Bool {
    return true

override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
    return (action == "copy:")

// MARK: - UIResponderStandardEditActions

override func copy(sender: AnyObject?) {
    UIPasteboard.generalPasteboard().string = text

Then in your view controller, you can add a long press gesture to your label:

let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: "handleLongPressGesture:")

and handle the long press with this method:

func handleLongPressGesture(recognizer: UIGestureRecognizer) {
     if let recognizerView = recognizer.view,
         recognizerSuperView = recognizerView.superview
         let menuController = UIMenuController.sharedMenuController()
         menuController.setTargetRect(recognizerView.frame, inView: recognizerSuperView)
         menuController.setMenuVisible(true, animated:true)

NOTE: This code is taken directly from the NSHipster article, I am just including it here for SO compliance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download