1

i'm new in Objective C, i have search bar in my tableView. I need no restrict input in my searchBar text field, for example i don't need to input more then 20 symbols, how can i do these?

in

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText

i try to write smth like

searchBar.text.lenght == 20;

but it's no use

how can i do these? or maybe it easier to turn off keyboard when lenght>20. Thank you.

3 Answers 3

10

You could use shouldChangeCharactersInRange:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
   return ([textField.text length] + [string length] - range.length > 20) ? NO : YES;
}

Edit: Sorry. For UISearchBar you have to use

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
   return ([searchBar.text length] + [text length] - range.length > 20) ? NO : YES;
}

Edit: See comment below

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
   return ([searchBar.text length] + [text length] - range.length <= 20);
}
2
  • The searchBarButtonClicked-Method would not called if I test that and reach the maximum char count. This works better for me: stackoverflow.com/a/7317394/701900
    – matzino
    Apr 10, 2014 at 10:45
  • 2
    just a stylistic thing: NO : YES is a bit ugly. why not test for <= 20 and drop the ? NO : YES Oct 10, 2014 at 14:10
4

For future reader, in Swift 4:

func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let totalCharacters = (searchBar.text?.appending(text).count ?? 0) - range.length
    return totalCharacters <= 20
}
0
2

Expanding on the other answer, since you are new to Objective-C

1.You will need to implement the UISearchBarDelegate protocol inside your view controller.

@interface ViewController : UIViewController <UISearchBarDelegate>

2. You will need to assign the delegate

searchBar.delegate = self

3. Implement the delegate callback as specified in the other post

If you want to hide the keyboard if you go over 20 characters, you can do it in the same delegate function by calling

[searchBar resignFirstResponder];
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.