0
我想在應用程序運行時以及在某段時間(例如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中創建一個靜態(只有一個)Timer。
我應該如何以正確的方式實現一個計時器?
(我使用的是Iphone7,雨燕和Xcode的最新版本)
創建爲類屬性,無效它第一次,然後用新的計時器 – Tj3n
代替@ Tj3n感謝,但我是很新的快速的,你可以舉一個例子或編輯上面 – theAlse
代碼時,你需要結束計時,通話'screenUnTouchedTimer.invalidate()',我在你的代碼中看到你沒有調用它 – Tj3n