How can we programmatically change the brightness of the iPhone screen?

前端 未结 3 2010
鱼传尺愫
鱼传尺愫 2020-12-06 04:59

How can I change the brightness of the screen programmatically using iPhone SDK?

相关标签:
3条回答
  • 2020-12-06 05:09
    [[UIScreen mainScreen] setBrightness: yourvalue];
    

    Requires iOS 5.0 or later. yourvalue is a float between 0.0 and 1.0.

    0 讨论(0)
  • 2020-12-06 05:10

    I had some problems with changing the screen brightness in viewDidLoad/viewWillDisappear so I created a singleton class to handle all the action. This is how I do it:

    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
        }
    }
    
    0 讨论(0)
  • 2020-12-06 05:27

    UPDATE: For Swift 3

    UIScreen.main.brightness = YourBrightnessValue
    

    Here's the swift answer to perform this

    UIScreen.mainScreen().brightness = YourBrightnessValue
    

    YourBrightnessValue is a float between 0.0 and 1.0

    0 讨论(0)
提交回复
热议问题