【问题标题】:How do i create a countdown timer in xcode 4.5 [closed]我如何在 xcode 4.5 中创建倒数计时器 [关闭]
【发布时间】:2012-09-22 06:18:13
【问题描述】:

好的,我想创建多个计时器,它们都在不同的时间(25、50、1 分钟、1 分钟 30 秒...)开始,但我不知道如何让它在达到 0 时停止,以及在达到 0 时停止,将“播放器”带到另一个视图。

这是我的 .h 文件

@interface ViewController :UIViewController {

IBOutlet UILabel *seconds;

NSTimer *timer;

int MainInt;
}

@end

这是我的 .m 文件

@implementation ViewController

-(void)countDownDuration {

MainInt -= 1;

seconds.text = [NSString stringWithFormat:@"%i", MainInt];

}

-(IBAction)start:(id)sender {

MainInt = 25;

timer = [NSTimer scheduledTimerWithTimeInterval:1.0

                                         target:self
                                       selector:@selector(countDownDuration)
                                       userInfo:nil
                                        repeats:YES];
}

@end

【问题讨论】:

    标签: objective-c ios xcode4.5


    【解决方案1】:

    NSTimer 不会自动执行此操作,但将其添加到您的 countDownDuration 方法很简单。例如:

    -(void)countDownDuration {
      MainInt -= 1;
      seconds.text = [NSString stringWithFormat:@"%i", MainInt];
      if (MainInt <= 0) {
        [timer invalidate];
        [self bringThePlayerToAnotherView];
      }
    }
    

    当然你想创建多个计时器。您可以将每个变量存储在不同的变量中,并为每个变量分配一个不同的选择器。但是如果你查看 NSTimer 的文档,回调方法实际上将定时器对象作为选择器;你忽略了它,但你不应该。

    同时,您可以将任何类型的对象存储为计时器的 userInfo,因此这是为每个计时器存储单独的当前倒计时值的好地方。

    所以,你可以这样做:

    -(void)countDownDuration:(NSTimer *)timer {
      int countdown = [[timer userInfo] reduceCountdown];
      seconds.text = [NSString stringWithFormat:@"%i", countdown];
      if (countdown <= 0) {
        [timer invalidate];
        [self bringThePlayerToAnotherView];
      }
    }
    
    -(IBAction)start:(id)sender {
      id userInfo = [[MyCountdownClass alloc] initWithCountdown:25];
      timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                               target:self
                                             selector:@selector(countDownDuration:)
                                             userInfo:userInfo
                                              repeats:YES];
    }
    

    我留下了一些未写的细节(比如MyCountdownClass 的定义——它必须包括做正确事情的方法initWithCountdown:reduceCountdown),但它们都应该非常简单。 (此外,您可能想要一个 userInfo 存储的不仅仅是倒计时值——例如,如果每个计时器将玩家发送到不同的视图,您也必须将视图存储在那里。)

    PS,注意你现在需要@selector(countDownDuration:)。 ObjC 的新手总是把这件事搞砸。 countDownDuration:countDownDuration 是完全不相关的选择器。

    PPS,MyCountdownClass 的完整定义必须在 countDownDuration: 中可见(除非您有其他具有相同选择器的类)。您可能希望将 userInfo 的结果显式转换为 MyCountdownClass * 以使事情更清晰。

    【讨论】:

    • 我在 int countdown = [[timer userInfo] reduceCountdown] 下得到这个错误;选择器“reduceCountdown”没有已知的实例方法
    • 嗯,是的,当你定义你的MyCountdownClass 时,你必须给它一个reduceCountdown 方法,否则你将无法在它上面调用reduceCountdown。很抱歉没有说得更清楚;我会编辑答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2014-01-04
    • 1970-01-01
    相关资源
    最近更新 更多