你可以使用shouldChangeCharactersInRange:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
return ([textField.text length] + [string length] - range.length > 20) ? NO : YES;
}
编辑:
对不起。对于 UISearchBar 你必须使用
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
return ([searchBar.text length] + [text length] - range.length > 20) ? NO : YES;
}
编辑:
见下面的评论
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
return ([searchBar.text length] + [text length] - range.length <= 20);
}