SwiftUIの基本を身につけたい方はこちら

【Xcode/Swift】UIScreen.mainが非推奨になった。’main’ will be deprecated in a future version of iOS

事象

UIScreen.mainを使おうとすると、以下の警告が表示されます。画面の横幅を、UIScreen.main.bounds.widthとかで取れる便利なものですが、、非推奨になっちゃったみたいですね。

‘main’ will be deprecated in a future version of iOS:
Use a UlScreen instance found through context instead: i.e, view.window.windowScene.screen

対応方法

これからは、以下のように使います。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
guard let window = UIApplication.shared.connectedScenes.first as? UIWindowScene else { return }
let screenSize = window.screen.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
guard let window = UIApplication.shared.connectedScenes.first as? UIWindowScene else { return } let screenSize = window.screen.bounds let screenWidth = screenSize.width let screenHeight = screenSize.height
guard let window = UIApplication.shared.connectedScenes.first as? UIWindowScene else { return }
let screenSize = window.screen.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

ちょっと長いので、私は以下のような構造体を別ファイルで作成して使っています。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
struct DisplayInfo {
private static var window: UIWindowScene? {
return UIApplication.shared.connectedScenes.first as? UIWindowScene
}
static var screenSize: CGRect {
return window?.screen.bounds ?? CGRect.zero
}
static var width: CGFloat {
return screenSize.width
}
static var height: CGFloat {
return screenSize.height
}
}
struct DisplayInfo { private static var window: UIWindowScene? { return UIApplication.shared.connectedScenes.first as? UIWindowScene } static var screenSize: CGRect { return window?.screen.bounds ?? CGRect.zero } static var width: CGFloat { return screenSize.width } static var height: CGFloat { return screenSize.height } }
struct DisplayInfo {
    private static var window: UIWindowScene? {
        return UIApplication.shared.connectedScenes.first as? UIWindowScene
    }
    
    static var screenSize: CGRect {
        return window?.screen.bounds ?? CGRect.zero
    }
    
    static var width: CGFloat {
        return screenSize.width
    }
    
    static var height: CGFloat {
        return screenSize.height
    }
}

使い方は簡単で、以下のようにDisplayInfo.widthというふうに書けます。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
struct SomeView: View {
var body: some View {
if DisplayInfo.width > 600 {
// 600ピクセル以上の幅のデバイスに対してのビュー
} else {
// それ以下のデバイスに対してのビュー
}
}
}
struct SomeView: View { var body: some View { if DisplayInfo.width > 600 { // 600ピクセル以上の幅のデバイスに対してのビュー } else { // それ以下のデバイスに対してのビュー } } }
struct SomeView: View {
    var body: some View {
        if DisplayInfo.width > 600 {
            // 600ピクセル以上の幅のデバイスに対してのビュー
        } else {
            // それ以下のデバイスに対してのビュー
        }
    }
}

評価