简体   繁体   English

UITextField 如何检查是否按下了删除键

[英]UITextField How to check if a delete key is pressed

I am implementing a search bar from my local database that searches from db as user enters info.The issue is that i concat recent character and the previous ones and then send it for search.How can I REMOVE the character (last one) when back key is pressed.I am using我正在从我的本地数据库中实现一个搜索栏,当用户输入信息时从 db 搜索。问题是我连接了最近的字符和以前的字符,然后将其发送以进行搜索。返回时如何删除字符(最后一个)键被按下。我正在使用

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

Thanks for the replies感谢您的回复

You can get the string that is supposed to be in text field after this method:您可以在此方法之后获取应该在文本字段中的字符串:

NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

And that newString you probably can use 'as is' for searching the database.而那个newString您可能可以“按原样”使用来搜索数据库。

If you just want to get the event when user deletes some characters in textField - then you can check it the following way:如果您只想在用户删除 textField 中的某些字符时获取该事件 - 那么您可以通过以下方式进行检查:

if ([string length] == 0 && range.length > 0)
  //Some characters deleted

for swift users:对于快速用户:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if string.characters.count == 0 && range.length > 0 {
        // Back pressed
        return false
    }

    return true
}

Better idea - in textField:shouldChangeCharactersInRange:replacementString: set up a conditional to return NO when there are no more characters...更好的主意 - 在 textField:shouldChangeCharactersInRange:replacementString: 设置一个条件以在没有更多字符时返回 NO...

if ((range.location == 0) && (string.length == 0))
{        
    NSLog(@"is cleared!");
    return NO;
}

return YES;
if (self.textView.text.length > 0) 
{ 
    [self.textView deleteBackward]; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM