问题描述
我有一个应用程序可以创建一个新颖的钟面。在主视图控制器中,我有一个一秒钟的计时器:
let _ = Timer.scheduledTimer(timeInterval: seconds,target: self,selector: #selector(timerHandler(_:)),userInfo: nil,repeats: true)
这会调用以下函数:
@objc func timerHandler(_ : Timer) {
self.clockShape.time = Date.init(timeIntervalSinceNow: 0)
}
在 clockShape
对象中,有代码使用 drawRect
绘制经过时间的形状。此外,还会显示小视图以显示形状的顶点。目标是让这些顶点在屏幕上停留一分钟,之后颜色会发生变化。当颜色改变时,一个新的动画开始将 alpha 淡化为 0,然后移除视图。为此,我尝试在 clockShape
对象代码中使用以下代码:
let v = UIView(frame: CGRect(x: 0,y: 0,width: 4,height: 4))
v.backgroundColor = UIColor.yellow.withAlphaComponent(0.5)
self.addSubview(v)
let seconds = 60.0
let _ = Timer.scheduledTimer(timeInterval: seconds,selector: #selector(timerHandler2(_:)),userInfo: v,repeats: true)
此处的 v
是显示 60 秒后颜色发生变化等的视图。这是在函数 timerHandler2
中完成的。
@objc func timerHandler2(_ timer: Timer) {
if let v = timer.userInfo as? UIView {
let duration:TimeInterval = 240.0
v.backgroundColor = UIColor.red.withAlphaComponent(1.0)
UIView.animate(withDuration: duration,delay: 0,options:[]) {
v.alpha = 0
} completion: { (finished) in
if finished {
// This is happening prematurely,apparently using the timer closure. It happens after 60 seconds instead of 240 seconds.
v.removeFromSuperview()
}
}
}
}
如果我注释掉 v.removeFromSuperview()
行,动画会继续并需要 240 秒。那么为什么要在 60 秒而不是 240 秒后执行完成块呢?显然,它是由 60 秒计时器触发的,但为什么呢?我通过从使用动画完成块更改为使用 removeFromSuperview()
在延迟后执行 DispatchQueue.main.asyncAfter
解决了这种情况。所以我不需要解决方案,只需要解释为什么会发生这种情况。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)