Janak Thakkar
Janak Thakkar

Reputation: 434

Disable cut, copy, paste on UITextField using IBInspectable

Please find the following code which did not work for me.

 @IBInspectable var pasteOption: Bool = true {
        didSet {
            func canPerformAction(action: Selector, withSender sender: AnyObject) -> Bool {
                if action == "selectAll:" {
                    return pasteOption
                }
                if action == "select:" {
                    return pasteOption
                }
                if action == "cut:" {
                    return pasteOption
                }
                if action == "copy:" {
                    return pasteOption
                }
                if action == "paste:" {
                    return pasteOption
                }
                return super.canPerformAction(action, withSender: sender)
            }
        }
    }

I want to disable cut, copy, paste on my UITextfield using IBInspectable.

Upvotes: 3

Views: 1170

Answers (1)

bcamur
bcamur

Reputation: 894

You need to define your var like this:

@IBInspectable var pasteOption: Bool = true

and then override your UITextField's canPerformAction function like this:

override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
    if action == "selectAll:" {
        return pasteOption
    }
    if action == "select:" {
        return pasteOption
    }
    if action == "cut:" {
        return pasteOption
    }
    if action == "copy:" {
        return pasteOption
    }
    if action == "paste:" {
        return pasteOption
    }
    return super.canPerformAction(action, withSender: sender)
}

By doing this you return the value of pasteOption for the specific actions defined in the function (which are selectAll, select, cut, copy and paste in this case) any time your text field opens up an edit menu.

Upvotes: 1

Related Questions