检测正在按下的删除键

Cra*_*aig 1 xcode objective-c ios

我已经四处寻找检测何时按下删除键的方法.我遇到了Apple的密钥处理文档,还有一些人尝试使用这些文档.我不确定采用哪种方法.我想做的很简单:

-(void)deleteKeyWasPressed {

if (myTextField.text.length == 0) {

[previousTextField becomeFirstResponder]; 

}

}
Run Code Online (Sandbox Code Playgroud)

但据我所知,这种方法不存在.

这样做的最佳方式是什么?

rma*_*ddy 7

iOS没有直接支持检测删除键(或Return以外的任何键).您可以做的最好的是实现textField:shouldChangeCharactersInRange:replacementString:委托方法.当用户点击Delete键时,替换字符串将是空字符串.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (string.length == 0) {
        // handle Delete (but this also handles the Cut menu as well)
    } else {
        // some other key or text is being pasted.
    }

    return YES;
}
Run Code Online (Sandbox Code Playgroud)