Disable TextFields actions in Swift

Posted By : Akshay Luthra | 08-Jun-2016



Hi, this blog will provide you step by step knowledge on how you can disable the most common actions of a TextField or TextView in Swift iOS apps. The TextFields actions that we will cover in this blog are “select, selectAll, cut, copy, paste, delete”.

 

First, you need to create a class which extends the UITextField :

import Foundation
import UIKit

class CustomUITextField: UITextField {
    override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
        if action == #selector(NSObject.select(_:)) {
            return false
        }
        if action == #selector(NSObject.selectAll(_:)) {
            return false
        }
        if action == #selector(NSObject.cut(_:)) {
            return false
        }
        if action == #selector(NSObject.copy(_:)) {
            return false
        }
        if action == #selector(NSObject.paste(_:)) {
            return false
        }
        if action == #selector(NSObject.delete(_:)) {
            return false
        }        
        return super.canPerformAction(action, withSender: sender)
    }
}
 

 

Second, wire the storyboard with your ViewController. You need to declare an @IBOutlet :

@IBOutlet var aboutTextField: CustomUITextField?
 

 

Third, follow the following steps :

1) Go to your storyboard

2) Click the target TextField

3) Select Identity Inspector

4) Change the class to CustomUITextField

 

 

This is all you need to do.

Thanks for reading this blog!

 

About Author

Author Image
Akshay Luthra

Akshay Luthra has excellent experience in developing Cross Platform Mobile Apps using JavaScript and Titanium Framework. He loves listening to music and travelling new places.

Request for Proposal

Name is required

Comment is required

Sending message..