2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Swift] UIScreen.mainを使わずに画面の明るさを設定する

Last updated at Posted at 2024-10-07

背景

UIScreen.mainがiOS17以降においてdeprecatedとなっていますが、UIScreen.main.brightnessを用いない画面輝度の設定についての情報があまりなかったのでメモとして残しておきます。

結論

windowScene.screen.brightnessを使おう

サンプルコードと補足

画面輝度を調節するだけなのであまり意味はないですが、windowSceneの取得を
guard let windowScene = UIApplication.shared..connectedScenes.first as? UIWindowScene
の形を避け、
view.window?.windowScene
の形をとっています。
(前者の実装だとiPadのマルチウィンドウ等、複数wIndowが存在する際に意図していないwindowを取得する可能性があるため)

SampleViewController.swift
import UIKit

final class SampleViewController: UIViewController {
    private var windowSchene: UIWindowScene?
    private var defaultBrightness: CGFloat?

    // viewWillAppearまでviewがnilなので、このタイミングで実行
    override func viewIsAppearing(_ animated: Bool) {
        super.viewIsAppearing(animated)
        windowScene = view.window?.windowScene
        defaultBrightness = windowScene?.screen.brightness
    }
}

private extension SampleViewController {
    func changeBrightness(to value: CGFloat) {
        guard let value else { return }
        windowScene?.screen.brightness = value
    }
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?