Scrollview线程计时器iphone

时间:2011-08-01 04:35:17

标签: iphone nstimer

  

可能重复:
  UIScrollView pauses NSTimer until scrolling finishes

我有一个滚动视图和一个标签来显示到目前为止的倒计时。我倒计时了,但每当我上下滚动滚动视图时,倒计时停止,但是当我松开手指时,它又开始工作了。我知道它与多线程有关。这是我的代码

-(void) viewdidload
{
    timer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];
}

-(void)updateLabel {


    NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *countdown = [calender  
                                   components:(NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) 
                                   fromDate:[NSDate date] 
                                   toDate:destDate 
                                   options:0];

    timerCountDown.text = [NSString stringWithFormat:@"%dday %dh %dm %ds", [countdown day],[countdown hour],[countdown minute],[countdown second]];
}

3 个答案:

答案 0 :(得分:1)

不要经历添加线程或其他线程的所有麻烦,而是简单地说:

  1. 手指向下/触摸开始。记录或保存当前时间 毫秒(A)
  2. On finger up / touchesEnded(?)录制或保存 当前时间(B)
  3. 从B中减去A错过/暂停 以毫秒为单位的时间,然后从计时器的时间中减去。
  4. 唯一的问题是,屏幕上的时钟会在滚动时暂停,但是一旦释放它就会更新或刷新。

    希望这能以比线程方式更简单的方式解决您的问题。 LH

答案 1 :(得分:0)

您可以通过以下方式将文本设置为UILabel。

NSString *cntTime = [NSString stringWithFormat:@"%dday %dh %dm %ds", [countdown day],[countdown hour],[countdown minute],[countdown second]];
[timerCountDown performSelectorOnMainThread:@selector(setText:) withObject:cntTime waitUntilDone:YES];

修改

该方法应为-(void)viewDidLoad

另外,给出一些时间间隔,比如1秒,

timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];

并且,你实现了任何UIScrollViewDelegate方法吗?

答案 2 :(得分:0)

Nideo的答案很好(只要你正在进行严格的倒计时,你就可以预测你所展示的东西的价值是多少)。但是,您可能会发现自己需要显示随机发生的事件计数。如果是这样,您可以实现scrollview委托方法scrollViewDidScroll:并从其源中刷新数据(即调用updateLabel)。您还可以将UIScrollView子类化并实现touchesBegan:/ touchesMoved:/ touchesEnded:,刷新每个中显示的值,然后将事件传递给super以允许正常的触摸处理。