Detect delete key using UIKeyCommand

3 Solutions Collect From Internet About “Detect delete key using UIKeyCommand”

Simple really – need to look for the backspace character “\b”

As people were having problems with Swift, I figured a small, complete example in both Objective C and Swift might be a good answer.

Note that Swift doesn’t have a \b escape character for backspace, so you need to use a simple Unicode scalar value escape sequence of \u{8}. This maps to the same old-school ASCII control character number 8—”control-H” for those of us old^H^H^Hmature enough to remember those days!—for backspace as \b does in Objective C.

Here’s an Objective C view controller implementation that catches backspaces:

#import "ViewController.h"

@implementation ViewController

// The View Controller must be able to become a first responder to register
// key presses.
- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (NSArray *)keyCommands {
    return @[
        [UIKeyCommand keyCommandWithInput:@"\b" modifierFlags:0 action:@selector(backspacePressed)]
    ];
}

- (void)backspacePressed {
    NSLog(@"Backspace key was pressed");
}

@end

And here’s the equivalent view controller in Swift:

import UIKit

class ViewController: UIViewController {

    // The View Controller must be able to become a first responder to register
    // key presses.
    override func canBecomeFirstResponder() -> Bool {
        return true;
    }

    func keyCommands() -> NSArray {
        return [
            UIKeyCommand(input: "\u{8}", modifierFlags: .allZeros, action: "backspacePressed")
        ]
    }

    func backspacePressed() {
        NSLog("Backspace key was pressed")
    }

}