xcode 如何检查 UITextfield 中是否包含文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11649971/
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-09-15 01:01:09  来源:igfitidea点击:

How to check if a UITextfield has Text in it?

iphonexcodeios5uitextfield

提问by Douglas

I just followed a tut on making a conversion app. It was good, but I wanted to expand on it. The tut has you input a value in for Fahrenheit and then converts to Celsius. Pretty basic. So I wanted to add a Kelvin conversion as well. But the code only let you plug in a number for the Fahrenheit. So after adding the Kelvin text field, I wanted to check to see which text box had text in it. So I used the following code:

我只是跟着制作了一个转换应用程序。这很好,但我想扩展它。啧啧,你输入一个华氏度的值,然后转换成摄氏度。非常基本。所以我也想添加开尔文转换。但是代码只允许您插入华氏度的数字。因此,在添加 Kelvin 文本字段后,我想查看哪个文本框中有文本。所以我使用了以下代码:

- (IBAction)convert:(id)sender 
{
if ([fahrenheit isFirstResponder]) 
{
    float x = [[fahrenheit text] floatValue];
    float y = (x - 32.0f) * (5.0f/9.0f);  //celcius
    float z = y + 273.15f;  //kelvin
    [celcius setText:[NSString stringWithFormat:@"%3.2f" , y]];
    [kelvin setText:[NSString stringWithFormat:@"%3.2f" , z]];
    [fahrenheit resignFirstResponder];
} else if ([celcius isFirstResponder])
{
    float x = [[celcius text] floatValue];
    float y = 32.0f + ((9.0f/5.0f) * x); //farenheit
    float z = x + 273.12f; //kelvin
    [fahrenheit setText:[NSString stringWithFormat:@"%3.2f" , y]];
    [kelvin setText:[NSString stringWithFormat:@"%3.2f" , z]];
    [celcius resignFirstResponder];
}else if ([kelvin isFirstResponder])
{
    float x = [[kelvin text] floatValue];
    float y = x - 273.15f; //celcius
    float z = 32.0f + ((9.0f/5.0f) * y); //farenheit
    [celcius setText:[NSString stringWithFormat:@"%3.2f" , y]];
    [fahrenheit setText:[NSString stringWithFormat:@"%3.2f" , z]];
    [kelvin resignFirstResponder];
}
}

This allowed me to input a number in any text field and then convert. But then I decided to dismiss the keyboard. My code said to resignFirstResponder. But then the convert action did not work because now there was no first responder. Any clues as to how I can check which text box has text in it, and then do the conversions? Thanks in advance for any help.

这允许我在任何文本字段中输入一个数字然后进行转换。但后来我决定关闭键盘。我的代码说要辞职FirstResponder。但是之后转换操作不起作用,因为现在没有第一响应者。关于如何检查哪个文本框中包含文本,然后进行转换的任何线索?在此先感谢您的帮助。

回答by Ayman Melhem

    if( [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] != nil &&  [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] != @"" )
        {

        // text field has text


// get text without white space

NSString * textWithoutWhiteSpace = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ;



        }

回答by TheTiger

This is for checking textView is empty or not:-

这是用于检查 textView 是否为空:-

if([textView.text isEqualToString:@""])
{
    //textView is Empty
}
else 
{
   //textView has text
}

If you want to check it for white space as well, first remove white spaces from string then check ... like this -

如果你也想检查它的空格,首先从字符串中删除空格然后检查......像这样 -

NSString *trimmedString = [tV.text stringByTrimmingCharactersInSet:
                           [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if([trimmedString isEqualToString:@""])
{
       NSLog(@"textView is empty");
}
else
{
    NSLog(@"textView has some value");
}

回答by RaffAl

Just use the hasTextmethod.

就用这个hasText方法吧。

Example:

例子:

if(_yourTextField.hasText)
{
    // Do something.
}

回答by Apurv

if(textView.text.length > 0)
{
   //text present
}
else
{
  //no text
}

回答by Moonkid

Better solution is make all conversions on the fly, add new action to all textFields

更好的解决方案是即时进行所有转换,向所有 textField 添加新操作

[textField addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged];

Then in method textChanged: do something like this:

然后在方法 textChanged: 做这样的事情:

- (void) textChanged:(UITextField *)tf {
    if (tf.text.floatValue > 0) {
        if (tf == fahrenheit) {
            //Do convertion for fahrenheit
        }
        .
        .
        .
        //etc.
    }
}

回答by Heavy_Bullets

On response to Meno's answer

关于对梅诺的回答的回应

DO NOT USE != @""

不要使用 != @""

this check for pointer equality vs String equality

此检查指针相等性与字符串相等性

use:

用:

[string isEqualToString:@""];

回答by Vincent

If you want to know it DURING input, and probably performs actions based on this info, you shall use:

如果您想在输入期间了解它,并可能根据此信息执行操作,则应使用:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

回答by narco

There were a few problems in some of the other answers, like they didn't use isEqualToString, and they superfluously removed potential characters from a string that we are only interested in if it is nil or not.

在其他一些答案中存在一些问题,例如他们没有使用 isEqualToString,并且他们从我们只关心是否为零的字符串中多余地删除了潜在的字符。

I don't have enough reputation to comment, so I am posting this as an answer.

我没有足够的声誉发表评论,所以我将其发布为答案。

For a similar issue, I used this to check each textfield that I needed to check for being empty:

对于类似的问题,我用它来检查我需要检查的每个文本字段是否为空:

- (BOOL) isEmpty:(UITextField*) field
{
    if (!(field.text) ||
       ([[field.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString: @""]))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

回答by Tom Howard

If you need an NSStringwith white space removed:

如果您需要NSString删除空格:

NSString *nonWhiteSpaceString = [textfield.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

Then you could use the length as a boolean:

然后你可以使用长度作为布尔值:

BOOL textFieldHasText = nonWhiteSpaceString.length;