Search code examples
xcodeinputuser-input

How to code for user typing input and use that in a formula?


I'm a student using Xcode 3.2 and What I need to know is how the user can type input and then I can use that input in a formula. I.e. the user inputs 5 and in another field 7 and then I use both numbers in a math formula to return a value

I'm new to C and C++ (I use java), and I have been searching the web for an answer and I somehow can't find what I'm looking for although it's a relatively simple concept. Code examples are definitely preferred and greatly appreciated.


Solution

  • Ok the best way to do this is to convert the numbers inputed into floats then do whatever math problem you want and then convert the answer into a string and display the string in a label. As you can see here in my .h file:

    IBOutlet UITextField *rectWidth;
    IBOutlet UITextField *rectLength;
    IBOutlet UILabel *rectResult;
    
    }
    
    @property (retain, nonatomic) UITextField *rectWidth;
    @property (retain, nonatomic) UITextField *rectLength;
    @property (retain, nonatomic) UILabel *rectResult;
    
    
    -(IBAction)calculate:(id)sender;
    

    As you can see I have 2 text fields for the user to input the data. Right now I was using it for an area and volume finder but you can name them whatever you want. Also I have the calculate action to tell the program what to do when the button is clicked. Then in your .m

    -(IBAction)calculate:(id)sender {
        float floatRectResult=[rectWidth.text floatValue]*
        [rectLength.text floatValue];
    
        NSString *stringRectResult=[[NSString alloc] 
                            initWithFormat:@"%1.2f",floatRectResult];
    
        rectResult.text=stringRectResult;
    
        [stringRectResult release];
    
    
    
    }
    

    So all you need to do is put this code in and change the * behind float floatRectResult=[rectWidth.text floatValue] to whatever formula you want to use. Like addition, subtraction division etc. So in interface builder connect the text fields to the two text fields and the label to the label on screen. Then create a button and link it to the IBAction calculate. And that should be all. Hope this helps.