How to know if a UITextField in iOS has blank spaces

前端 未结 9 696
一整个雨季
一整个雨季 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条回答
  • 2020-12-01 04:24

    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
        }
    }
    
    0 讨论(0)
  • 2020-12-01 04:29

    In Swift,

    if you want to restrict the user, you can use contains()

    For Example,

    if userTextField.text!.contains(" "){
    //your code here.....
    }
    
    0 讨论(0)
  • 2020-12-01 04:32

    Heres Swift 3 version

    let whitespaceSet = NSCharacterSet.whitespaces
    let range = string.rangeOfCharacter(from: whitespaceSet)
    if let _ = range {
        return false
    }
    else {
        return true
    }
    
    0 讨论(0)
提交回复
热议问题