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

前端之家收集整理的这篇文章主要介绍了iPhone – 如何检查UITextfield中是否包含文本?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我只是在制作转换应用程序时啧啧称道.这很好,但我想扩展它.你输入一个华氏值,然后转换为摄氏度.很基本的.所以我也希望添加开尔文转换.但是代码只允许你插入一个华氏数字.因此,在添加开尔文文本字段后,我想检查哪个文本框中包含文本.所以我使用了以下代码

- (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",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];
}
}

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

解决方法

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



        }

猜你在找的Xcode相关文章