Search code examples
iosswiftiphone

Why cannot I set UIScreen.main.brightness?


I just started making a new app. The code UIScreen.main.brightness = 1.0 does not work anywhere. I tried it in viewDidLoad, tried it in viewWillAppear. I commented out everything else and making this the only line of code that is run, but it is not working. I cannot change brightness. I am trying it on a real device which is my iPhone X - iOS 13.4.1. What could be the reason?

Edit:Also tried with a new Xcode project. Still does not work.


Solution

  • I notice that in iOS 13, calls to UIScreen.main.brightness from viewDidLoad and viewWillAppear don't have any effect. Adding it to viewDidAppear works fine.

    It also worked fine putting in button action.

    import UIKit
    
    class ViewController: UIViewController {
        var brightness: CGFloat = 1.0
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
            let button = UIButton(type: .infoDark)
    
            // This call is ignored
            UIScreen.main.brightness = CGFloat(0.3)
            view.addSubview(button)
            button.frame = CGRect(x: 40.0, y: 100.0, width: button.frame.width, height: button.frame.height)
            button.addTarget(self, action: #selector(toggle), for: .touchUpInside)
        }
    
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
    
            // This call is also ignored
            UIScreen.main.brightness = CGFloat(0.8)
        }
    
        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
    
            // This call sets the brightness
            UIScreen.main.brightness = 0.5
        }
    
        @objc func toggle() {
            brightness = brightness - 0.2
            print("brightness is \(brightness)")
            if brightness < 0 { brightness = 1.0 }
            // This call changes the brightness
            UIScreen.main.brightness = brightness
        }
    
    }