swiftcopyuitextfielduipasteboard

Detect if user copied text from textfield


I want to use the word that user copies from my app textfield.

I found this code:

NotificationCenter.default.addObserver(self, selector: #selector(clipboardChanged), name: UIPasteboard.changedNotification, object: nil)

But 'clipboardChanged' function not calling when copying text from textfield.

I use Swift 4.2


Solution

  • This Code Just Worked Fine For Me:

        override func copy(_ sender: Any?) {
            super.copy()
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
            NotificationCenter.default.addObserver(self, selector: #selector(clipboardChanged), name: UIPasteboard.changedNotification, object: nil)
        }
    
        @objc func clipboardChanged(){
            print("Cut/Copy Performed")
        }
    

    There are many ways of achieving copy Notification

    1. UIMenuController

    Displays a menu with Copy, Cut, Paste, Select, and Select All commands above or below the selection.

    Refer:

    https://developer.apple.com/documentation/uikit/uimenucontroller

    https://nshipster.com/uimenucontroller/

    2. UIResponderStandardEditActions Protocol

    Responders implement methods declared in this informal protocol to handle the chosen menu commands (for example, copy: and paste:). Since your UIViewController inherits from UIResponder which indeed conforms to UIResponderStandardEditActions, so it will give you error saying Redundant conformance. So just implement the methods you need directly.

    Refer: https://developer.apple.com/documentation/uikit/uiresponderstandardeditactions

    3. UIPasteboard changedNotification

    class let changedNotification: NSNotification.Name
    

    This happens at the same time the pasteboard’s change count (changeCount property) is incremented. Changes include the addition, removal, and modification of pasteboard items.

    Refer: https://developer.apple.com/documentation/uikit/uipasteboard