はじめに
よくある画面表示中は輝度を最大にして非表示にしたら輝度戻して!っていう要望がきた!
そのときにちょっとハマったのでメモ。。。
輝度設定
輝度の変更には下記を使うらしい。
var brightness: CGFloat { get set }
簡単やん!と思い下記のように実装してみた
final class SecondViewController: UIViewController {
/// 元の輝度を保持
private let defaultScreenBrightness = UIScreen.main.brightness
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
changeScreenBrightnessToMax()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
restoreScreenBrightness()
}
@objc private func willEnterForeground(_ notification: Notification) {
changeScreenBrightnessToMax()
}
@objc private func didEnterBackground(_ notification: Notification) {
restoreScreenBrightness()
}
private func changeScreenBrightnessToMax() {
UIScreen.main.brightness = 1.0
}
private func restoreScreenBrightness() {
UIScreen.main.brightness = defaultScreenBrightness
}
}
viewWillAppear
と viewWillDisappear
、willEnterForeground
と didEnterBackground
で輝度操作をしてるのでこれで完璧!と思いきやバックグラウンドにいったときに輝度が戻っていない
修正版
どうやら didEnterBackground
では画面輝度を操作できないようです。。。(公式ドキュメントはちょっと探せなかった。。。)おそらくアプリがバックグラウンドにいる状態では画面輝度を操作できないようです(たぶんそれが正しいと思います)didEnterBackground
だとアプリがすでにバックグラウンドに入っているので入る直前に処理してやる必要があります。
didEnterBackground
の代わりに willResignActive
を使いましょう!
こんな感じ
final class SecondViewController: UIViewController {
/// 元の輝度を保持
private let defaultScreenBrightness = UIScreen.main.brightness
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willResignActiveNotification(_:)), name: UIApplication.willResignActiveNotification, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
changeScreenBrightnessToMax()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
restoreScreenBrightness()
}
@objc private func willEnterForeground(_ notification: Notification) {
changeScreenBrightnessToMax()
}
@objc private func willResignActiveNotification(_ notification: Notification) {
restoreScreenBrightness()
}
private func changeScreenBrightnessToMax() {
UIScreen.main.brightness = 1.0
}
private func restoreScreenBrightness() {
UIScreen.main.brightness = defaultScreenBrightness
}
}
これで解決
おわりに
画面輝度はシミュレーターでは操作できないので処理が呼ばれていることだけ確認してコミットした不幸な出来事でした。。。(ちゃんと実機で確認しましょう!)