计数按到UIButton

时间:2011-04-02 16:37:28

标签: iphone cocoa-touch

我在XIB中有UILabelUIButton,我希望UILabel能够反映用户按下UIButton的次数,例如当我单击按钮时,标签显示1,当我再次单击它时,它显示2。

由于

2 个答案:

答案 0 :(得分:3)

-(IBAction)buttonPressed
{
    static int count;
    count++;
    label1.text = [NSString stringWithFormat:@"%d", count];
}

答案 1 :(得分:3)

标题(.h)文件:

#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

实施(.m)档案:

#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

所以基本上:
- 创建名为Sample
的基于窗口的新应用程序 - 编辑SampleAppDelegate.m和SampleAppDelegate.h - 将Label连接到Interface Builder中的UILabel - 将UIButton连接到Interface Builder中的按钮
- 最后点击Build and Run