Michael Smith
Michael Smith

Reputation: 1

How do I make 2 labels add together with each other?

Hi I'm kinda new to Xcode and I'm trying to make an app where you press a button and the number will go up; and I have 2 buttons and 2 labels. I've got it to where the 2 labels will count up, but now I'm wanting the numbers from both labels to add together and show in a different label. Is there any line I can add to the buttons to make them just count up in the other label as well or do I need to have a separate action and/or button?

Thanks

Upvotes: 0

Views: 2145

Answers (2)

ozz
ozz

Reputation: 1137

esqew's answer would do the trick, but the format specifier is incorrect.

If the variable sum is in fact an int ...

label3.text = [NSString stringWithFormat:@"%@", sum];

should be:

label3.text = [NSString stringWithFormat:@"%d", sum];

%@ is for Objective-C objects, an int is not an Objective-C object.

Reference:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html

Upvotes: 0

esqew
esqew

Reputation: 44699

Straight up:

int sum = [[label1 text] intValue] + [[label2 text] intValue];
label3.text = [NSString stringWithFormat:@"%@", sum];

Should work, just make sure to replace the pointers I used with the ones you're using.

Upvotes: 1

Related Questions