Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS

Aaron Watkins
PLUS
Aaron Watkins
Courses Plus Student 10,500 Points

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

Aaron Watkins
PLUS
Aaron Watkins
Courses Plus Student 10,500 Points

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,650 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)
    }
}