(IBAction)button to label output

2020-05-06 19:28发布

问题:

hi im new in iphone SDK object C programming.. this question i want to ask is that , how can i run a program with 2 buttons (increment 1 and decrement 2) to be shown the result in a label. with the result is changing everytime i click increment1 or decrement1. sorry im very new in object c progamming, hoping u can help me :) thank you

-mark

回答1:

It is very easy to implement once you get a bit familiar with Objective C and Xcode. But my advice is get a bit familiar with these so that it would be also easy for fellow developers to help you explain.

I hope you have created a trial project to kick-start with. It would be having .h .m and .xib files.

  1. Take two UIButtons and one UILabel in you xib file.

  2. Connect the Buttons and lable's outlet to your nib file.

  3. Add the following code in your .h and .m files.

Code for .h File

@interface RootViewController :     UIViewController<> {
IBOutlet UIButton *incrBtn;
IBOutlet UIButton *decrBtn;
IBOutlet UILabel *label;
NSInteger counter;

}

-(IBAction)incr;
-(IBAction)decr; 

Code for .m file

- (void)viewDidLoad {
[super viewDidLoad];
counter=0;
label.text=[NSString stringWithFormat:@"%d",counter];
}

-(IBAction)incr{
counter++;
label.text=[NSString stringWithFormat:@"%d",counter];


}

-(IBAction)decr{
counter--;
label.text=[NSString stringWithFormat:@"%d",counter];


}

And that's it!



回答2:

Note: These are the basic things that you can get through googling itself. Check this link.

Hints for your scenario:

-Create a view with 2 buttons, 1 label

-Set the IBOutlet label

-Set tag for each buttons

-Assign a same action[say -(IBAction) buttonAction: (id)sender] for both buttons,

-Have one global integer varible(say val)

-Code as follows

-(IBAction)buttonAction: (id)sender
{
 UIButton *but=(UIButton *)sender;
 if(but.tag==1)
 {
   val++;
   [label setText:[NSString stringWithFormat:"%@"],val];
 }
 else
 {
   val--;
   [label setText:[NSString stringWithFormat:"%@"],val];
 }
}