2011-04-02 44 views
1

我有一個UILabel和一個UIButton在XIB中,我希望UILabel反映用戶按下UIButton的次數,例如,當我按一下按鈕,標籤顯示1,當我再次點擊它,它顯示2.計數按到UIButton

感謝

回答

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

你需要與IB建立一些連接,如使用方法 – Robin 2011-04-02 16:42:01

+0

「static int count;」的標籤和按鈕事件連接的IBOutlet,是否會在再次調用該方法時使其持續存在?我的意思是爲什麼不只是'label1.text = [NSString stringWithFormat:@「%d」,([label1.text intValue] + 1)];' – 2011-04-02 16:56:20

+0

是的,它不止於此,通過計數靜態值它會自動變爲0(我從大學時候就記得的東西) – Robin 2011-04-02 16:58:13

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 

所以基本上:
- 創建與T新的基於窗口的應用程序他樣品名稱
- 編輯SampleAppDelegate.m和SampleAppDelegate.h
- 連接theLabel到的UILabel在Interface Builder
- 在UIButton的連接theButton在Interface Builder
- 最後打到編譯和運行

當然