UIViewController intercept copy/paste actions of UITextView

241 Views Asked by At

I have a UITextView inside a UIViewController. I want to intercept (or override) cut/copy/paste and other UIEdit actions in UITextView in my UIViewController. I tried the following code in my UIViewController subclass but it doesn't seems to invoke my custom copy/paste functions.

  override var canBecomeFirstResponder: Bool {
    return true
  }

  override func copy(_ sender: Any?) {
      NSLog("Copy called")
  }

   override func paste(_ sender: Any?) {
       NSLog("Paste called")
   }

Can someone tell me what I am doing wrong and what needs to be done to invoke the above copy/paste functions?

1

There are 1 best solutions below

2
Jayachandra A On

So, here your responder chain is not proper to handle the copy, paste and other

In-oder to achieve your requirement you can create a custom textView class and add that to your view of ViewController

class UserEventsTextView: UITextView {

    override var canBecomeFirstResponder: Bool {
      return true
    }

    override func copy(_ sender: Any?) {
        NSLog("Copy called")
    }

     override func paste(_ sender: Any?) {
         NSLog("Paste called")
     }

}