【SwiftUI/iOS】SafeAreaInsets, StatusBarの高さを取得

目次

概要

iPhoneX以降、画面の上下に若干の隙間ができる。
この領域はUIなどを配置しないように気をつけなければならない。
時にはその領域の大きさを必要とする時があるので、取得方法を記載しておく。

また、時間や充電の残量を表示しているステータスバーの高さの取得方法も記載しておく。

ソースコード

import SwiftUI

@main
struct TestApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            InterfaceTestView()
        }
    }
}
import SwiftUI

struct InterfaceTestView: View {
    
    private var safeAreaInsets: UIEdgeInsets {
        let scenes = UIApplication.shared.connectedScenes
        let windowScene = scenes.first as? UIWindowScene
        return windowScene?.windows.first?.safeAreaInsets ?? .zero
    }
    
    var body: some View {
        GeometryReader { geometry in
            Color.yellow
            VStack {
                Text("画面サイズ")
                Text("幅:\(UIScreen.main.bounds.width) 高さ:\(UIScreen.main.bounds.height)")
                
                Text("SafeArea")
                Text("上:\(safeAreaInsets.top)")
                Text("下:\(safeAreaInsets.bottom)")
                Text("左:\(safeAreaInsets.left)")
                Text("右:\(safeAreaInsets.right)")
                
                Text("SafeAresサイズ(黄色部分)")
                Text("幅:\(geometry.size.width) 高さ:\(geometry.size.height)")
            }
        }
    }
}

スクリーンショット

詳細

今回、詳細は特に記載することがない。
なぜなら、表示した通りだから。

参考ページ