Reputation: 570
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.
Upvotes: 1
Views: 6350
Reputation: 3069
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
}
Upvotes: 4
Reputation: 947
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);
}
Upvotes: 10
Reputation: 16855
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];
Upvotes: 2