I'm fairly new to coding with Objective-C/Xcode, so I'm just trying my luck with the easy stuff, making sure I get it before moving on to something harder.
What I am trying at the moment is to make a calculator. I've done one of those simple ones where there are two text boxes and an equals button, so I'm trying a number pad calculator now.
What I'm stuck on is how to ADD a number开发者_JAVA百科 to a label (NEXT TO ALL THE OTHER NUMBERS, NOT ADDED) when the corresponding button is pressed. I can manage to add one number, but not both.
At the moment, I am only experienced with vb.net, so I'm used to
label.text = label.text & 1
I'm not sure how to do this is in Xcode.
Any help, code hints, links (or code chunks :P) would be appreciated.
Don't add the number to the label. Instead, have another variable which is your running total which is a number and then update the label with the text version of the number. A good habit to get into is separating your presentation (view) from your data (model). In this trivial example, create a variable to hold your data and make the UI reflect that. Don't use the label as your model.
As a simple code example, let's say I had an increment button and I wanted it to increment the value of the label. The action for the button is the IBAction increment function.
Header:
@interface CrapletViewController : UIViewController
{
NSInteger _total;
}
@property (nonatomic, retain) IBOutlet UIButton *myButton;
@property (nonatomic, retain) IBOutlet UILabel *label;
- (IBAction)increment:(id)sender;
Implemenation:
- (IBAction)increment:(id)sender
{
_total++;
NSLog(@"total");
[label setText:[NSString stringWithFormat:@"total: %d", _total]];
}
label.text = [[NSNumber numberWithInt:([label.text intValue] + 1)] stringValue];
精彩评论