在UITextField中接收错误消息

时间:2011-08-06 17:21:59

标签: iphone objective-c ios4 iphone-sdk-3.0 cocos2d-iphone

当我试图计算两个UITextField的百分比时,我在UITextField中收到一条消息“NAN”。我目前的代码如下:

float firstFloat = [self.tex15.text floatValue]; 
float secondFloat = [self.tex16.text floatValue]; 
float answer = secondFloat / firstFloat * 100;
self.tex20.text = [NSString stringWithFormat:@"%.1f%%",answer];

2 个答案:

答案 0 :(得分:1)

NaN表示不是数字。它表示您的计算不会产生有效数字。我的第一个猜测是firstFloat0,这意味着你试图除以零。反过来,这可能是由self.tex15 nil造成的 - 请检查您的IBOutlet是否已正确连接。

答案 1 :(得分:0)

我强烈怀疑这与您的IBOutlet连接有关。以下代码适用于我:

@interface testViewController : UIViewController {
    UITextField *tf1;
    UITextField *tf2;
    UILabel *result;
}

@end

@implementation testViewController

- (void)dealloc{
    [tf1 release];
    [tf2 release];
    [result release];
    [super dealloc];
}

-(void) click:(id) obj {
    float firstFloat = [tf1.text floatValue]; 
    float secondFloat = [tf2.text floatValue]; 
    float answer = secondFloat / firstFloat * 100;
    result.text = [NSString stringWithFormat:@"%.1f%%",answer];
}

-(void) viewWillAppear:(BOOL)animated {

    tf1 = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, 200, 30)];
    tf1.backgroundColor = [UIColor whiteColor];

    tf2 = [[UITextField alloc]initWithFrame:CGRectMake(10, 50, 200, 30)];
    tf2.backgroundColor = [UIColor whiteColor];

    result = [[UILabel alloc]initWithFrame:CGRectMake(10, 90, 200, 30)];
    result.backgroundColor = [UIColor whiteColor];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(10, 130, 50, 30);
    [btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];

    [self.view addSubview:tf1];
    [self.view addSubview:tf2];
    [self.view addSubview:result];

}

@end