rai*_*212 15 iphone objective-c nstimer
我有一个倒数计时器的应用程序.我已经使用一个标签更新了这个标签,这个标签是用定时器调用的函数更新的:
...
int timeCount = 300; // Time in seconds
...
NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(actualizarTiempo:) userInfo:nil repeats:YES];
...
- (void)actualizaTiempo:(NSTimer *)timer {
timeCount -= 1;
if (timeCount <= 0) {
[timer invalidate];
} else {
[labelTime setText:[self formatTime:timeCount]];
}
}
Run Code Online (Sandbox Code Playgroud)
注意:formatTime是一个接收整数(秒数)并返回格式为mm:ss的NSString的函数
一切正常,也就是说,时间倒计时但问题是我在应用程序中有一个UITableView,如果我触摸桌面并拖动它(沿着单元格移动),计时器会停止,直到我从屏幕上松开手指...
这种行为是否正常?如果是,是否有任何方法可以避免它并在拖动表时使计时器工作?
ser*_*gio 28
通过使用scheduledTimerWithTimeInterval:,如j.tom.schroeder所说,您的计时器将自动安排在默认模式的主运行循环上.当您的运行循环处于非默认模式时(例如,点击或滑动时),这将阻止您的计时器触发.
但是,解决方案不是使用线程,而是为所有常见模式安排计时器:
NSTimer *timer = [NSTimer timerWithTimeInterval:1
target:self
selector:@selector(actualizarTiempo:)
userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
Run Code Online (Sandbox Code Playgroud)
根据您希望在没有停止计时器的情况下允许的事件类型,您也可以考虑UITrackingRunLoopMode.有关运行循环模式的详细信息,请参阅Apple Docs.
这是 Swift 版本:
雨燕2
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "removeFromSuperview", userInfo: nil, repeats: false)
NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
Run Code Online (Sandbox Code Playgroud)
斯威夫特 3、4、5
var timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(removeFromSuperview), userInfo: nil, repeats: false)
RunLoop.main.add(timer, forMode: RunLoop.Mode.common)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3663 次 |
| 最近记录: |