Detect delete key using UIKeyCommand

跟風遠走 提交于 2019-12-21 03:44:09

问题


Anyone know how to detect the "delete" key using UIKeyCommand on iOS 7?


回答1:


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", or ^H in caret notation) 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 {

    override var canBecomeFirstResponder: Bool {
        return true;
    }

    override var keyCommands: [UIKeyCommand]? {
        return [
            UIKeyCommand(input: "\u{8}", modifierFlags: [], action: #selector(backspacePressed))
        ]
    }

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

}



回答2:


Simple really - need to look for the backspace character "\b"




回答3:


You can always try UIKeyInput. https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIKeyInput_Protocol/index.html#//apple_ref/occ/intfm/UIKeyInput/deleteBackward

The function should be

- (void)deleteBackward



来源:https://stackoverflow.com/questions/22068308/detect-delete-key-using-uikeycommand

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!