Reputation: 1335
I am learning Xcode(objective C). I want to make simple calculator.
I started by adding four simple buttons and one label. Two buttons are for numbers(1 and 2), and I added variables into .m file:
int *one = 1;
int *two = 2;
Next step what I've done is that I made action on button clicked and said that label take value from that button:
self.firstLabel.text=[NSString stringWithFormat:@"%d", one);
And I made same action for another button.
Everything is fine until this step, what I want to do next is when I click on number button to add value to that label, then when I click to divide(/) button to add / sign and when I click to another button to add another value.
I want to be something like this in label: 2 / 1, and when i click = button to divide them and show result. Thanks.
EDIT:
I also added label proper into .h, and when I click on button it shows me only one value in label.
Upvotes: 1
Views: 562
Reputation: 3503
Since you are just starting to learn obj C you may want to keep your calculator simple, building a fully functional calc. can get surprisingly complex. You should consider using an RPN approach, it will make things much easier, you can just push the numbers to a stack and perform operations one at a time. Something like: 2, enter, 1, enter + enter.
You may also want to have a look at Stanford's iOS course on Apple University, the course is in Swift but the class project was a calculator so it should give you a good reference point. Hope that helps and good luck!
Upvotes: 1
Reputation: 650
You are only setting the int value to the label. You need to append the value maintaining the previous text so that it appears as "2 / 1". I'll suggest using tags for the buttons and use a common method for number buttons in your calculator. This is more sort of logical thing rather than specific to iOS and Xcode. Similarly when "=" is pressed use a method to calculate the result.
Upvotes: 0
Reputation: 353
you should add a custom target for each button, i.e.,
- (IBAction)addDivide:(id)sender {
self.firstLabel.text = [[NSString alloc] initWithFormat:@"%@ /", self.firstLabel.text];
}
Any action will update your label.
Just a further advice for you, don't name the label as "firstLabel", try to give it a name tied to its semantics.
Upvotes: 0