Counting presses to a UIButton
开发者_运维知识库I have a UILabel
and a UIButton
in a XIB, and I want the UILabel
to reflect the number of times the user has pressed the UIButton
, e.g. when I click the button, the label shows 1, when I click it again, it shows 2.
Thanks
-(IBAction)buttonPressed
{
static int count;
count++;
label1.text = [NSString stringWithFormat:@"%d", count];
}
Header (.h) file:
#import <UIKit/UIKit.h>
@interface SampleAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
IBOutlet UILabel * theLabel;
int count;
}
- (IBAction)theButton:(id)sender;
@property (nonatomic, retain) IBOutlet UIWindow *window;
@end
Implementation (.m) file:
#import "SampleAppDelegate.h"
@implementation SampleAppDelegate
@synthesize window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
count = 0;
theLabel.text = [NSString stringWithFormat:@"%d", count];
[self.window makeKeyAndVisible];
return YES;
}
- (IBAction)theButton:(id)sender {
count++;
theLabel.text = [NSString stringWithFormat:@"%d",count];
}
- (void)dealloc {
[window release];
[super dealloc];
}
@end
So basically:
- Create new window-based app with the name Sample
- Edit SampleAppDelegate.m and SampleAppDelegate.h
- Connect theLabel to the UILabel in Interface Builder
- Connect the UIButton to theButton in Interface Builder
- Finally hit Build and Run
精彩评论