使用UIKeyCommand检测删除密钥

时间:2014-02-27 12:18:14

标签: ios cocoa uikeycommand

任何人都知道如何在iOS 7上使用UIKeyCommand检测“删除”密钥?

3 个答案:

答案 0 :(得分:17)

由于人们遇到Swift的问题,我认为在Objective C和Swift中都有一个小而完整的例子可能是一个很好的答案。

请注意,Swift没有退格的\b转义字符,因此您需要使用\u{8}的简单Unicode标量值转义序列。对于退格,这会映射到相同的旧学校ASCII control character编号8(“control-H”或{H} {H} \b

这是一个捕获退格的Objective C视图控制器实现:

#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

这是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")
    }

}

答案 1 :(得分:15)

简单 - 需要查找退格字符“\ b”

答案 2 :(得分:-2)