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:
- (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.
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]];
}