How to know if a UITextField in iOS has blank spaces

前端 未结 9 812
一整个雨季
一整个雨季 2020-12-01 03:33

I have a UITextField where user can enter a name and save it. But, user should not be allowed to enter blank spaces in the textFiled.

1 - How can I find out,

9条回答
  •  萌比男神i
    2020-12-01 04:11

    if you really want to 'restrict' user from entering white space

    you can implement the following method in UITextFieldDelegate

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range     replacementString:(NSString *)string { 
    
        NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];
        NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
        if  ([resultingString rangeOfCharacterFromSet:whitespaceSet].location == NSNotFound)      {
            return YES;
        }  else  {
            return NO;
        }
     }
    

    If user enter space in the field, there is no change in the current text

提交回复
热议问题