Monday, September 10, 2012

Ví dụ Hướng dẫn tạo đồng hồ đếm ngược trong iphone bằng NSTimer

1. Khởi tạo một project CountTimeDown
2. Kéo vào 1 cái UILable và 3 UIButton như hình vẽ
Click image for larger version. 

Name: Screen Shot 2012-08-14 at 2.10.17 PM.jpg 
Views: 7 
Size: 7.4 KB 
ID: 1
3. Trong file .h

Mã:
@interface ViewController : UIViewController
{
    IBOutlet UILabel * lbTimer;
    NSTimer * myTimer;
}
-(IBAction)start:(id)sender;
-(IBAction)stop:(id)sender;
-(IBAction)reset:(id)sender;
-(void) showAction;

@end

4. Trong file .m
Mã:
-(IBAction)start:(id)sender
{
    myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showAction) userInfo:nil repeats:YES];
}
-(IBAction)stop:(id)sender
{
    [myTimer invalidate];
}
-(IBAction)reset:(id)sender
{
    lbTimer.text = @"80";
}
-(void) showAction
{
    int current = [lbTimer.text intValue];
    int newtime = current - 1;
    if (newtime < 10) {
        lbTimer.text = [NSString stringWithFormat:@"0%d", newtime];
    } else {
        lbTimer.text = [NSString stringWithFormat:@"%d", newtime];
    }
    if (newtime == 0) {
        [myTimer invalidate];
    }
    
}



==> như vậy các bạn đã tạo được cái đồng hồ đếm ngược trong iphone

chúc các bạn thành công:

No comments:

Post a Comment