我想在应用程序运行时要调暗电话屏幕,并且如果某个时间段内没有触摸事件(例如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 ......