Tel Tel - 4 months ago 29x
Swift Question

What function to call to undo a change made in a UITextField?

In the shortcut bar of iOS virtual keyboard there is an undo button that undoes the editing. Is there a way to associate an arbitrary button to that function?

Tel Tel

Here is the solution I implemented (the same can be done for the redo function).

import UIKit

class ViewController: UIViewController, UITextViewDelegate {

 @IBAction func undoButtonPressed(sender: AnyObject) {

    func enableDisableUndoButton() { // to disable or enable the button when needed
        if mainTextField.undoManager?.canUndo == true {
            undoButton.enabled = true
        } else {
            undoButton.enabled = false

    func textViewDidChange(mainTextField: UITextView) { // monitors when user makes changes in the text field


To get undoManager to take notes of the text changes made via code on the field, I use this:

mainTextField.replaceRange((theRange), withText: newStr)