iPhone restrict user from entering space in textfield

前端 未结 6 1978
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-05 08:40

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

- (BOOL)textField:(UITextField *)textField shouldChangeCharacters         


        
6条回答
  •  执念已碎
    2021-01-05 09:19

    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;
        }
    }
    

提交回复
热议问题