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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8238691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:33:13  来源:igfitidea点击:

How to know if a UITextField in iOS has blank spaces

iphoneiosipadnsstringuitextfield

提问by A for Alpha

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.

我有一个 UITextField,用户可以在其中输入名称并保存。但是,不应允许用户在 textFiled 中输入空格。

1 - How can i find out 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)

编辑 - 仅输入空格(空格)无效

回答by DarkDust

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 的解决方案。

回答by 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

如果用户在字段中输入空格,则当前文本没有变化

回答by Narayana

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

回答by Yevhen Dubinin

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

回答by DreamWatcher

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

回答by Pankaj Gaikar

Heres Swift 3 version

这是 Swift 3 版本

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

回答by Arnlee Vizcayno

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

回答by DZenBot

@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. Hope this helps anybody!

我声明了一个名为 whitespaceCount 的局部变量来保持空格的计数。希望这可以帮助任何人!

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