I have two variables from 1 to 100. I have two buttons. I want one button to print the two variables on the screen and I want one button to print the sum of both the variables. How do I do this? My code is:
- (IBAction)addition:(id)se开发者_Python百科nder;
{
int x = arc4random() %100;
int y = arc4random() %100;
[label1 setText: [NSString stringWithFormat:@"%i", x]];
[label2 setText: [NSString stringWithFormat:@"%i", y]];
}
- (IBAction)answer:(id)sender;
{
int z;
z = x+y;
answer.text = [[NSString alloc] initWithFormat:@"%i", z];
}
With the way you hace your code configured now, you'd have to declare your int
values in your Interface file (".h
file"). It'd look something like this pseudocode:
@interface Class {
int x;
int y;
UILabel *label1;
UILabel *label2;
UILabel *answer;
}
-(IBAction)...
Then in your .m
file, you'd just keep it as-is (just remove the int
declarations for x
and y
) and hook up the functions and the outlets in Interface Builder.
If you make x
and y
instance variables of the class in question you should get what you want.
As-is those variables don't exist after the invocation to addition:
and the above code doesn't even compile... unless you also happen to have x
and y
already declared as ivars in the class and the versions in addition:
are just shadowing them.
In either case, remove the int
from x
and y
in addition:
.
I guess you might have problem with answer button... But that should also work... but if not then try below code which should definitely work.
Here you should declare x
& y
variable in .h
file. And dont declare in addition button click.
- (IBAction)answer:(id)sender;
{
int z;
z = x+y;
answer.text = [NSString stringWithFormat:@"%i", z];
}
If you are not having this question, then i would suggest you to please specify exact issue that you are facing..
Assuming your are ensuring label1 and label2 keeps integer values your answer method can be like
- (IBAction)answer:(id)sender;
{
[answer setText:[NSString stringWithFormat:@"%i",[[label1 text] intValue] + [[label2 text] intValue]]];
}
精彩评论