problem while validation text field after
i need to validate a textfield input that allows two digits after a .
.
Eg: if i enter 2.333 it wont allow if can able to allow 2.33 only.
for that i use this code
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSArray *sep = [textField.text componentsSep开发者_开发知识库aratedByString:@"."];
if([sep count]==2)
{
NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
return !([sepStr length]=2);
}
}
if i use return !([sepStr length]=2)
it works fine that wont allow to enter next value.
But if i remove value also text field wont allow any modifications. i mean there is no user interaction. It can't able to edit. can any one please help me. How can i correct this. Thank u in advance.
The problem with the code by Thomas Clayson is that the user still can't edit the text field anymore when he types for example: "1234" and after that inserts a "." between 1 and 2, or if he pastes a number in the textfield.
Here's a better solution:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *sep = [newString componentsSeparatedByString:@"."];
if([sep count]>=2)
{
NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
return !([sepStr length]>2);
}
return YES;
}
Your problem could be that you aren't evaluating the return. You have a single =
and that is setting the value rather than evaluating the expression. This will always cause the function to return false in your case.
Here is my edit anyway:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSArray *sep = [textField.text componentsSeparatedByString:@"."];
if([sep count]==2)
{
NSString *sepStr=[NSString stringWithFormat:@"%@%@",[sep objectAtIndex:1],replacementString];
return !([sepStr length]>2);
}
}
All I've changed was to add (NSString *)string
onto the current text value of the textField and then tested to see if it was more than 2 characters.
精彩评论