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,
Use following lines of code
NSString *str_test = @"Example ";
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if([str_test rangeOfCharacterFromSet:whitespaceSet].location!=NSNotFound)
{
NSLog(@"Found");
}
if you want to restrict user use below code
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string isEqualToString:@" "])
{
return NO
}
else
{
return YES
}
}
In Swift,
if you want to restrict the user, you can use contains()
For Example,
if userTextField.text!.contains(" "){
//your code here.....
}
Heres Swift 3 version
let whitespaceSet = NSCharacterSet.whitespaces
let range = string.rangeOfCharacter(from: whitespaceSet)
if let _ = range {
return false
}
else {
return true
}