Search code examples
iosswiftuilabel

Does UILabel have any value to make it selectable?


Does UILabel 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.


Solution

  • 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:")
    label.addGestureRecognizer(gestureRecognizer)
    

    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)
             recognizerView.becomeFirstResponder()
         }}
    

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