cocos2d-iphone 制作倒计时功能

第一步:

将时间数字转换成字符串"00:00"的格式

声明这个方法不是我写的,我是在找资料的时候无意中看到的,想到自己也要将时间格式成字符串,就借鉴过来用了。

- (NSString *)stringForObjectValue:(id)anObject{

if (! [anObject isKindOfClass: [NSNumber class]]) {

return nil;

}

NSNumber *secondsNumber = (NSNumber*) anObject;

int seconds = [secondsNumber intValue];

int minutesPart = seconds / 60;

int secondsPart = seconds % 60;

NSString *minutesString = (minutesPart < 10) ?

    [NSString stringWithFormat:@"0%d", minutesPart] :

    [NSString stringWithFormat:@"%d", minutesPart];

NSString *secondsString = (secondsPart < 10) ?

    [NSString stringWithFormat:@"0%d", secondsPart] :

    [NSString stringWithFormat:@"%d", secondsPart];

return [NSString stringWithFormat:@"%@:%@", minutesString, secondsString];

}


第二部:

cocos2d中制作倒计时功能

之前介绍了使用自制的字符数字来显示倒计时。但没有介绍倒计时的功能如何实现。其实很简单的。现在将代码贴上来

        CCLabelAtlas *timeNumber = [CCLabelAtlas labelWithString:@"00:00" charMapFile:@"numbers.png" itemWidth:20 itemHeight:26 startCharMap:'0'];

        timeNumber.position = ccp(850, 690);

        [self addChild:timeNumber z:1 tag:3];

现在页面中加入一个倒计时牌默认的样子。给他一个tag值。

NSDate *time = [[NSDate dateWithTimeIntervalSinceNow:(30*60)] retain];

设置一个时间,30分钟到计时

[self schedule:@selector(updateTimeDisplay) interval:1];

然后使用cocos2d中的定时器,1秒钟执行一次updateTimeDisplay这个方法

- (void) updateTimeDisplay{

        int times = (int)[time timeIntervalSinceNow];

计算现在的剩余时间是多少

        CCLabelAtlas *clockLabel = (CCLabelAtlas *)[self getChildByTag:3];

通过tag取得CCLabel

        [clockLabel setString:[self stringForObjectValue:[NSNumber numberWithInt: times]]];

将新的剩余时间设置到页面中

        if(times <= 0){

            [self unschedule:@selector(updateTimeDisplay)];

如果没有剩余时间了,定时器也就不需要了,删除定时器

        }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值