September 30, 2025 (18 days ago)
iPhone SE のような Home Indicator がないデバイスでは、画面下端に余白(Safe Area)が存在しません。そのため、下部に配置したボタンやツールバーがギリギリまで寄ってしまうことがあります。
この問題を解決するために、@Environment
を活用して「bottom Safe Area が存在するかどうか」を判定できるプロパティを自作してみましょう。
import SwiftUI
import UIKit
private struct HasBottomSafeAreaKey: EnvironmentKey {
static var defaultValue: Bool {
let bottomInset = UIApplication.shared
.connectedScenes
.compactMap { $0 as? UIWindowScene }
.flatMap { $0.windows }
.first(where: \.isKeyWindow)?
.safeAreaInsets.bottom ?? 0
return bottomInset > 0
}
}
extension EnvironmentValues {
var hasBottomSafeArea: Bool {
get { self[HasBottomSafeAreaKey.self] }
set { self[HasBottomSafeAreaKey.self] = newValue }
}
}
これで @Environment(\.hasBottomSafeArea)
が使えるようになります。
struct ContentView: View {
@Environment(\.hasBottomSafeArea) private var hasBottomSafeArea
var body: some View {
VStack {
Spacer()
Button("Action") {
// do something
}
.padding(.bottom, hasBottomSafeArea ? 0 : 16)
}
}
}
padding
は不要