Reputation: 1986
I have a UITextField
that my user uses to type out tags. I need to be able to at a very specific time - stop my user from continuing to type in the keyboard that is presented by default with UITextFields. However, I need my user to still be allowed to hit the backspace button on the iOS keyboard so that they can try and type a word that will fit.
A couple VERY important things to keep in mind:
UITextField
should not be frozen due to a maximum amount of characters, because I am determining when the textField should be frozen based off of UIViews that I am adding to the screen for the tagsI have tried setting the textField.enabled = NO
, but once again, I need to still be able to use the textField, I just simply need to freeze the typing and force the user to backspace, not allowing andy characters to be added to the textField
.
Upvotes: 1
Views: 536
Reputation: 2693
Try this
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// Prevent crashing undo bug – see note below.
if(range.length + range.location > textField.text.length)
{
return NO;
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;
if(textField == self.yourTextField)
{
return newLength <= CHARACTER_LIMIT;
}
else
{
return YES;
}
}
Upvotes: 1
Reputation: 637
Try this, Back space will work even if the textfield pre populated with more than MAX_Length text
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range
replacementString: (NSString*) string {
NSString *text = [textField.text stringByReplacingCharactersInRange:range withString: string];
NSString *text = [textField.text stringByReplacingCharactersInRange:range withString: string];
if([text length] > MAX_LENGTH && string.length>0)
return NO;
else
return YES;
}
Upvotes: 0
Reputation: 2126
You could try something like below
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range
replacementString: (NSString*) string {
NSString *text = [textField.text stringByReplacingCharactersInRange:range withString: string];
if([text length] > MAX_LENGTH)
return NO;
else
return YES;
}
EDIT1: To this delegate method get called, set the textfield's delegate. In this case, you can use it as
yourTextField.delegate = self;
In your viewWillAppear/viewDidAppear.
Upvotes: 3