简体   繁体   English

如何知道 iOS 中的 UITextField 是否有空格

[英]How to know if a UITextField in iOS has blank spaces

I have a UITextField where user can enter a name and save it.我有一个 UITextField,用户可以在其中输入名称并保存。 But, user should not be allowed to enter blank spaces in the textFiled.但是,不应允许用户在 textFiled 中输入空格。

1 - How can I find out,if user has entered two blank spaces or complete blank spaces in the textFiled 1 - 我如何知道用户是否在 textFiled 中输入了两个空格或完整的空格

2 - How can i know if the textFiled is filled only with blank spaces 2 - 我怎么知道 textFiled 是否只填充了空格

edit - It is invalid to enter only white spaces(blank spaces)编辑 - 仅输入空格(空格)无效

You can "trim" the text, that is remove all the whitespace at the start and end.您可以“修剪”文本,即删除开头和结尾的所有空格。 If all that's left is an empty string, then only whitespace (or nothing) was entered.如果剩下的只是一个空字符串,那么只输入了空格(或什么都不输入)。

NSString *rawString = [textField text];
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimmed = [rawString stringByTrimmingCharactersInSet:whitespace];
if ([trimmed length] == 0) {
    // Text was empty or only whitespace.
}

If you want to check whether there is any whitespace (anywhere in the text), you can do it like this:如果你想检查是否有任何空格(文本中的任何地方),你可以这样做:

NSRange range = [rawString rangeOfCharacterFromSet:whitespace];
if (range.location != NSNotFound) {
    // There is whitespace.
}

If you want to prevent the user from entering whitespace at all, see @Hanon's solution.如果您想完全阻止用户输入空格,请参阅@Hanon 的解决方案。

if you really want to 'restrict' user from entering white space如果你真的想“限制”用户输入空白

you can implement the following method in UITextFieldDelegate您可以在 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如果用户在字段中输入空格,则当前文本没有变化

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

UPD: Swift 2.0 Support UPD: Swift 2.0 支持

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let whitespaceSet = NSCharacterSet.whitespaceCharacterSet()
    let range = string.rangeOfCharacterFromSet(whitespaceSet)
    if let _ = range {
        return false
    }
    else {
        return true
    }
}

I had a same condition not allowing user to input blank field我有一个相同的条件不允许用户输入空白字段

Here is my code and check statement这是我的代码和检查语句

- (IBAction)acceptButtonClicked:(UIButton *)sender {
if ([self textFieldBlankorNot:fullNametext]) {
        fullNametext.text=@"na";
    }
// saving value to dictionary and sending to server

}

-(BOOL)textFieldBlankorNot:(UITextField *)textfield{
    NSString *rawString = [textfield text];
    NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimmed = [rawString stringByTrimmingCharactersInSet:whitespace];
    if ([trimmed length] == 0)
        return YES;
    else
        return NO;
}

Heres Swift 3 version这是斯威夫特 3 版本

let whitespaceSet = NSCharacterSet.whitespaces
let range = string.rangeOfCharacter(from: whitespaceSet)
if let _ = range {
    return false
}
else {
    return true
}

@Hanon's answer is the pretty neat, but what I needed was to allow at least 1 white space, so based on Hanon's solution I made this one: @Hanon 的回答非常简洁,但我需要的是允许至少 1 个空格,所以基于 Hanon 的解决方案,我做了这个:

I declared a local variable called whitespaceCount to keep the counts of the white spaces.我声明了一个名为 whitespaceCount 的局部变量来保持空格的计数。 Hope this helps anybody!希望这可以帮助任何人!

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range     replacementString:(NSString *)string 
{ 
    NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];

    if ([string rangeOfCharacterFromSet:whitespaceSet].location != NSNotFound) 
    {
        whitespaceCount++;
        if (whitespaceCount > 1) 
        {
            return NO;
        }
    }
    else 
    {
        whitespaceCount = 0;
        return YES;
    }
}

Here's what I did using stringByReplacingOccurrencesOfString .这是我使用stringByReplacingOccurrencesOfString

- (BOOL)validateFields
 {
      NSString *temp = [textField.text stringByReplacingOccurrencesOfString:@" "
                                                          withString:@""
                                                             options:NSLiteralSearch
                                                               range:NSMakeRange(0, textField.text.length)];

      if ([temp length] == 0) {
          // Alert view with message @"Please enter something."
          return NO;
      }
 }

In Swift,在斯威夫特,

if you want to restrict the user, you can use contains()如果要限制用户,可以使用contains()

For Example,例如,

if userTextField.text!.contains(" "){
//your code here.....
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM