在我的应用程序设置中,有一个开关允许用户打开或关闭iPhone的闪光灯(闪光灯用于在应用程序运行时指示应用程序逻辑中的某些点)。我想要实现的是:当用户打开这个开关时,我想让它闪烁一秒钟,以指示它的“开”状态。
现在,我知道如何将torchMode
设置为开或关--这是在应用程序本身中实现的,但我不确定如何正确地将其设置为“闪烁”。我想到的一种方法是使用以下代码(toggleFlash()
是在主代码中实现的切换torchMode
的静态方法):
UIView.animate(withDuration: 1.0, animations: {
ViewController.toggleFlash(on: true)
}, completion: { (_) in
ViewController.toggleFlash(on: false)
})
这确实会让它“眨眼”,但只有一秒钟--而不是一秒。此外,我也不确定使用animate
来实现这一目的是否正确。另一个想法是使用Thread.sleep
,但这看起来是一个更糟糕的做法。
有人能推荐更好的解决方案吗?
发布于 2018-01-30 19:36:52
你可以用计时器。
func flashForOneSecond() {
ViewController.toggleFlash(on: true)
flashOffTimer = Timer.scheduledTimer(timeInterval:1, target:self, selector:#selector(self.switchFlashOff), userInfo:nil, repeats:false)
}
@objc func switchFlashOff() {
ViewController.toggleFlash(on: false)
}
发布于 2018-01-30 19:39:35
可能是这样的:
func flash() {
ViewController.toggleFlash(on: true)
let time = DispatchWallTime.now() + DispatchTimeInterval.seconds(1)
DispatchQueue.main.asyncAfter(wallDeadline: time) {
ViewController.toggleFlash(on: false)
}
}
wallDeadline是可靠的,解决方案被打包在一个函数中。
https://stackoverflow.com/questions/48520257
复制相似问题