Keyboard is not responding after implementing UISearchBar delegate method

独自空忆成欢 提交于 2019-12-02 11:58:39

问题


I have an UISearchBar which i implemented in my viewDidLoad: by code. I have also set the UISearchBarDelegate.

Now i want to restrict the user from entering more than 5 chracter So i implement this delegate method

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{

    NSLog(@"shouldChangeTextInRange");

    if (searchBar.text.length >= 5)
        return NO;

    return YES;
}

Its working fine.

The problem is when i typed upto 5 chracters & try to use the keyboard Backspace character, it is not working.

Also now if i pressed Search button in keyboard the searchBarSearchButtonClicked: is not getting called.

I am currently using

XCode version :3.2.5

iOS SDK :4.2


回答1:


You should do your test on the new text length (then length of the text that you will have if the suggested text change is applied), not the actual text length.

For that, you first need to compute the new text :

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
        return YES; // accept validation button

    NSString* newText = [searchBar.text stringByReplacingCharactersInRange:range withString:text];

    if (newText.length >= 5)
        return NO;

    return YES;
}



回答2:


You can't use backspace because of your code. after typing 5 characters, your searchBar is stuck. Use it instead :

    if ([textField.text length] + [string length] - range.length > 5) {
        return NO;
    }


来源:https://stackoverflow.com/questions/7316766/keyboard-is-not-responding-after-implementing-uisearchbar-delegate-method

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