Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Disable paste in UITextField/UITextView (Swift)

Hi everyone. I'm trying to disable the option to paste text in UITextFields and UITextViews throughout my application. searches online suggest that the below code would work if put into my ViewController, however, when testing I am still able to paste. Does anyone see what I might be overlooking?

Thank you!

 override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
        UIMenuController.sharedMenuController().menuVisible = false
        println("performaction")
        if action == "paste:" {
            println("no paste")
            return false
        }
        return super.canPerformAction(action, withSender:sender)
    }

1 Answer

Ugh! just figured this out seconds after posting. Rather than delete it, I'll share what I did here in case others need it. It was actually quite simple - just create a subclass of UITextField (or UITextView) and add that code pasted in the question to it. Then in your storyboard, just assign each UITextField (or UITextView) to that class you created. done. There may be a more efficient way to handle all UITextFields/UITextViews at once, but I'm not aware of it. Hope this helps someone.

Chris Shaw
Chris Shaw
26,676 Points

I searched around and this is the most accepted solution to the problem as canPerformAction is the gateway to the action menu.

EDIT: Just for clarity the solution is as follows.

import UIKit

class CustomTextField: UITextField {
    override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
        if action == "paste:" {
            return false
        }

        return super.canPerformAction(action, withSender: sender)
    }
}