Razattax
Razattax

Reputation: 163

Swift: Disable or Clear Undo for a TextField

When selecting NumberPad for a TextField, the iPad displays a full keyboard, so I have created a function to simply remove all characters that are not numeric. However, if a Non-numeric key is pressed and then the user presses Undo on the keyboard, the App Crashes.

How do I disable the Undo function for the TextField or at least clear the Undo Stack?

Upvotes: 1

Views: 2607

Answers (2)

Razattax
Razattax

Reputation: 163

The answer was simple in the end, I used undoManager removeAllActions, but instead of just needing:

undoManager?.removeAllActions()

as a line, I needed:

myTextField.undoManager?.removeAllActions()

I placed this in the DidChange Action for the TextField.

Upvotes: 2

Saqib Omer
Saqib Omer

Reputation: 5477

Add UITextFieldDelegate in your controller. In your viewDidLoad() assign yourTextField.delegate = self. Than implement this method

public func textFieldShouldClear(textField: UITextField) -> Bool{
    return false // This will disable clear button
}

Also for replacing text I would suggest use

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{//Your Logic Here
  }

Upvotes: 0

Related Questions