如何使用iPhone SDK以编程方式更改屏幕亮度?
答案 0 :(得分:48)
[[UIScreen mainScreen] setBrightness: yourvalue];
需要iOS 5.0或更高版本。 yourvalue 是介于0.0和1.0之间的浮点数。
答案 1 :(得分:10)
更新:适用于Swift 3
UIScreen.main.brightness = YourBrightnessValue
这是执行此操作的快速答案
UIScreen.mainScreen().brightness = YourBrightnessValue
YourBrightnessValue是0.0
和1.0
答案 2 :(得分:1)
我在viewDidLoad / viewWillDisappear中更改屏幕亮度时遇到了一些问题,因此我创建了一个单例类来处理所有操作。我就是这样做的:
import Foundation
import UIKit
final class ScreenBrightnessHelper {
private var timer: Timer?
private var brightness: CGFloat?
private var isBrighteningScreen = false
private var isDarkeningScreen = false
private init() { }
static let shared = ScreenBrightnessHelper()
func brightenDisplay() {
resetTimer()
isBrighteningScreen = true
if #available(iOS 10.0, *), timer == nil {
brightness = UIScreen.main.brightness
timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) { (timer) in
UIScreen.main.brightness = UIScreen.main.brightness + 0.01
if UIScreen.main.brightness > 0.99 || !self.isBrighteningScreen {
self.resetTimer()
}
}
}
timer?.fire()
}
func darkenDisplay() {
resetTimer()
isDarkeningScreen = true
guard let brightness = brightness else {
return
}
if #available(iOS 10.0, *), timer == nil {
timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) { (timer) in
UIScreen.main.brightness = UIScreen.main.brightness - 0.01
if UIScreen.main.brightness < brightness || !self.isDarkeningScreen {
self.resetTimer()
self.brightness = nil
}
}
timer?.fire()
}
}
private func resetTimer() {
timer?.invalidate()
timer = nil
isBrighteningScreen = false
isDarkeningScreen = false
}
}