0

In my case, I would restrict search bar text up to 50 characters. So I used shouldChangeTextInRange

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

But searchBarSearchButtonClicked is not called when search bar text more than 50 characters.

How do I handle this?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Mani Apple
  • 63
  • 7

1 Answers1

2

do like

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

Edit:

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
   return ([searchBar.text length] + [text length] - range.length <= 50);
}

at the same time check

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;

for additional reference

Community
  • 1
  • 1
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
  • Anbu, Thanks for your response. But my issue is not resolved. If the text length is less than 50 means, keyboard search button working correctly. If more than 50 means, it doesn't work. Because the `shouldChangeTextInRange` delegate return NO, so it doesn't call the `searchBarSearchButtonClicked` deleagate. Can you please give me any other solutions ? – Mani Apple Nov 02 '15 at 07:06
  • @ManiApple -- the condition is statified when you enter more than 50 it automatocally resingn , if you erase some char it works, but you need the answer like that whatever user types you need to enable the keyborad correct, when use press the resign button want to statisfy the condition – Anbu.Karthik Nov 02 '15 at 07:19
  • I'm using the UISearchBar, so that keyboard has search key. I don't want to resign the keyboard. Why it wont work when shouldChangeTextInRange return NO. Any clue...? How do I call searchBarSearchButtonClicked delegate more than 50 chars ? – Mani Apple Nov 02 '15 at 08:25