加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – NSTimer问题

发布时间:2020-12-14 17:15:11 所属栏目:百科 来源:网络整理
导读:所以我试图建立一个基本的计时器,但我失败了.基本上我想要的是在用户点击按钮时启动60秒计时器,并用剩余时间更新标签(如倒计时).我创建了我的标签和按钮并将它们连接到IB中.接下来,我为按钮创建了一个IBAction.现在,当我尝试根据计时器更新标签时,我的应用程
所以我试图建立一个基本的计时器,但我失败了.基本上我想要的是在用户点击按钮时启动60秒计时器,并用剩余时间更新标签(如倒计时).我创建了我的标签和按钮并将它们连接到IB中.接下来,我为按钮创建了一个IBAction.现在,当我尝试根据计时器更新标签时,我的应用程序搞砸了.这是我的代码:

NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 1
                      target: self
                      selector:@selector(updateLabelDisplay)
                      userInfo: nil repeats:YES];

我还有一个updateLabelDisplay函数,用于确定计时器运行的次数,然后从60减去该数字,并在倒计时标签中显示该数字.谁能告诉我我做错了什么?

解决方法

好的,对于初学者来说,如果你还没有,请检查一下: Official Apple Docs about Using Timers

根据您的描述,您可能希望代码看起来像这样.我对行为做了一些假设,但你可以适应品味.

此示例假定您要保留对计时器的引用,以便您可以暂停它或其他内容.如果不是这种情况,您可以修改handleTimerTick方法,以便将NSTimer *作为参数,并在计时器到期后使用它来使计时器失效.

@interface MyController : UIViewController
{
  UILabel * theLabel;

  @private
  NSTimer * countdownTimer;
  NSUInteger remainingTicks;
}

@property (nonatomic,retain) IBOutlet UILabel * theLabel;

-(IBAction)doCountdown: (id)sender;

-(void)handleTimerTick;

-(void)updateLabel;

@end

@implementation MyController
@synthesize theLabel;

// { your own lifecycle code here.... }

-(IBAction)doCountdown: (id)sender
{
  if (countdownTimer)
    return;


  remainingTicks = 60;
  [self updateLabel];

  countdownTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self selector: @selector(handleTimerTick) userInfo: nil repeats: YES];
}

-(void)handleTimerTick
{
  remainingTicks--;
  [self updateLabel];

  if (remainingTicks <= 0) {
    [countdownTimer invalidate];
    countdownTimer = nil;
  }
}

-(void)updateLabel
{
  theLabel.text = [[NSNumber numberWithUnsignedInt: remainingTicks] stringValue];
}


@end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读