views:

494

answers:

4

hi , i want to restrict user from entering space in a UITextField. for this i m using this code

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ( string == @" " ){
     UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"Error" message:@"You have entered wrong input" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
     [error show];
     return NO;
    }
    else {
     return YES;
    }
}

but it is not working .... what is wrong in it ?

+3  A: 

The problem is

string == @" "

is wrong. Equality for strings is done using:

[string isEqualToString:@" "]

:).

kiyoshi
While this is true, its not going to tell you whether your replacement string contains a space, it will just tell you if the replacement string is a single space.
crackity_jones
+1  A: 

Try this (set this in your - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string):

NSArray *escapeChars = [NSArray arrayWithObjects:@" ", nil];

NSArray *replaceChars = [NSArray arrayWithObjects:@"",nil];
int len = [escapeChars count];
NSMutableString *temp = [[textField text] mutableCopy];
for(int i = 0; i < len; i++) {
    [temp replaceOccurrencesOfString: [escapeChars objectAtIndex:i] withString:[replaceChars objectAtIndex:i] options:NSLiteralSearch range:NSMakeRange(0, [temp length])];
}
[textField setText:temp];
return TRUE;
Tim van Elsloo
+1  A: 
string == @" "

Isn't that just going to compare the adress of each of string and @" "? Thats not the comparison you want to do.

Also do you want to prevent them from entering a string that is just a space? If so then you need to change that == into a proper string comparison and you are good to go. If not and you want to prevent all spaces in an input string then you need a string matcher

hhafez
+3  A: 

This will search to see if your replacement string contains a space, if it does then it throws the error message up, if it doesn't it returns YES.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
    NSRange spaceRange = [string rangeOfString:@" "];
    if (spaceRange.location != NSNotFound)
    {
     UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"Error" message:@"You have entered wrong input" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [error show];
        return NO;
    } else {
     return YES;
    }
}
crackity_jones