iosswiftuilabeluipasteboard

I want native iOS copy and paste UI on UILabel


I want to create the native Copy and Paste experience that iOS provides when you tap and hold a UITextField - but I want it to work on a UILabel instead of a UITextField.

Is this possible, or is it something that only works with UITextField? Would I need to create my own custom UI and mess around in UIPasteboard or is there a more eloquent solution?

Here is a typical example, although it normally also shows the zoomed in circle:

A typical example of how it looks on a text field:


Solution

  • It is difficult to do the standard copy menu on the label. Or maybe at that time I tried but didnt succeed. So I just implemented a complete copy solution. I did it something like below:

    import UIKit
    
    class KGCopyableLabel: UILabel {
        
        override public var canBecomeFirstResponder: Bool {
            get {
                return true
            }
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            setup()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            setup()
        }
    
        func setup() {
            isUserInteractionEnabled = true
            addGestureRecognizer(UILongPressGestureRecognizer(
                target: self,
                action: #selector(showCopyMenu(sender:))
            ))
        }
    
        override func copy(_ sender: Any?) {
            UIPasteboard.general.string = text
            UIMenuController.shared.hideMenu()
        }
    
        @objc func showCopyMenu(sender: Any?) {
            becomeFirstResponder()
            let menu = UIMenuController.shared
            if !menu.isMenuVisible {
                menu.showMenu(from: self, rect: bounds)
            }
        }
    
        override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
            return (action == #selector(copy(_:)))
        }
    }
    

    You can then simple drag drop the label in Storyboard and make its type KGCopyableLabel and it should work.