我想在我的应用程序运行时调暗手机屏幕,并且在特定时间段(例如 10 秒)内没有触摸事件,然后在再次触摸屏幕上的任何位置时立即使屏幕变亮。
搜索后,似乎我需要创建一个自定义 UIApplication
才能处理所有触摸。以下是到目前为止我的代码:
import UIKit
@objc(MyApplication)
class MyApplication: UIApplication {
override func sendEvent(_ event: UIEvent) {
var screenUnTouchedTimer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.makeScreenDim), userInfo: nil, repeats: true);
// Ignore .Motion and .RemoteControl event simply everything else then .Touches
if event.type != .touches {
super.sendEvent(event)
return
}
// .Touches only
var restartTimer = true
if let touches = event.allTouches {
// At least one touch in progress? Do not restart timer, just invalidate it
self.makeScreenBright()
for touch in touches.enumerated() {
if touch.element.phase != .cancelled && touch.element.phase != .ended {
restartTimer = false
break
}
}
}
if restartTimer {
// Touches ended || cancelled, restart timer
print("Touches ended. Restart timer")
} else {
// Touches in progress - !ended, !cancelled, just invalidate it
print("Touches in progress. Invalidate timer")
}
super.sendEvent(event)
}
func makeScreenDim() {
UIScreen.main.brightness = CGFloat(0.1)
print("makeScreenDim")
}
func makeScreenBright() {
UIScreen.main.brightness = CGFloat(0.5)
print("makeScreenBright")
}
}
打印输出看起来像这样:
makeScreenBright
Touches in progress. Invalidate timer
makeScreenBright
Touches ended. Restart timer
makeScreenDim
makeScreenDim
makeScreenDim
makeScreenDim
makeScreenDim
...
正如您在上面看到的,代码存在很大问题,似乎我正在为每个触摸事件创建一个新的计时器。我不知道如何在 UIApplication 中创建静态(只有一个)计时器。
我应该如何以正确的方式实现一个计时器?
(我使用的是Iphone7,最新版本的swift和xcode)
最佳答案
您必须在某个地方使之前创建的计时器无效,否则您将得到您所描述的行为。
每次调用 sendEvent 时将其存储在属性中,以便您可以在下次调用该方法时访问它。
class MyApplication: UIApplication {
var screenUnTouchedTimer : Timer?
override func sendEvent(_ event: UIEvent) {
screenUnTouchedTimer?.invalidate()
screenUnTouchedTimer = Timer ......
关于ios - 当应用程序一段时间不使用时调暗显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41236874/