Cue
Cue

Reputation: 3092

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?

Upvotes: 1

Views: 1636

Answers (2)

Cue
Cue

Reputation: 3092

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) {
        mainTextField.undoManager?.undo()
        enableDisableUndoButton()
    }

    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
        enableDisableUndoRedoButtons()
    }

}

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

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

Upvotes: 1

William Kinaan
William Kinaan

Reputation: 28819

From iOS 8, shaking the device should trigger the undo operation. Your view controller should be the first responders so it can response to the undo trigger. You can have that by becoming the first responder one the view is about to appear and then resign it when it is about to disappear

override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        becomeFirstResponder()
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        resignFirstResponder()
    }
    override func canBecomeFirstResponder() -> Bool {
        return true
    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }

Upvotes: 1

Related Questions