🧐 iPhone Safe Area 크기 가져오기
Safe area의 배경색을 지정하고 싶다면, 메인 View의 BackgroundColor를 지정해주면 된다.
하지만 아래 화면처럼 상/하단이 동시에 적용이 되어버린다.
나는 아래쪽만 적용하고 싶어서, UIView를 코드로 각각 생성해서 addSubview()로 추가해주는 방식으로 해결을 했다.
(더 좋은 방법이 있는지는 찾아보는 중...)
그런데 노치가 없는 디자인의 아이폰은 하단 Safe Area가 없으므로,
현재 화면상의 Safe Area의 크기를 받아와서 처리해줘야 할 필요가 있다.
그래서 아이폰의 상/하단 Safe Area의 크기를 가져와 활용할 수 있는 코드를 찾아보았다.
if #available(iOS 13.0, *) {
let window = UIApplication.shared.windows.first
let top = window?.safeAreaInsets.top
let bottom = window?.safeAreaInsets.bottom
print("top : \(String(describing: top))")
print("bottom : \(String(describing: bottom))")
} else if #available(iOS 11.0, *) {
let window = UIApplication.shared.keyWindow
let top = window?.safeAreaInsets.top
let bottom = window?.safeAreaInsets.bottom
print("top : \(String(describing: top))")
print("bottom : \(String(describing: bottom))")
}
출처: https://es1015.tistory.com/457
위 코드를 사용하면 사이즈를 옵셔널 타입으로 잘 가져올 수는 있었다.
그런데, Xcode에서 아래와 같은 경고창이 표시되었다.
'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead
"UIApplication.shared.windows" 는 iOS15부터 사용이 중지되었다는 말인가보다.
앞으로는 "UIWindowScene.windows"를 사용하라고 친절히 알려주기까지 하고 있다.
그래서 다음과 같이 코드를 수정해서 사용했다.
let scenes = UIApplication.shared.connectedScenes
let windowScene = scenes.first as? UIWindowScene
if let hasWindowScene = windowScene {
print("top: ", hasWindowScene.windows.first?.safeAreaInsets.top ?? 0.0)
print("bottom: ", hasWindowScene.windows.first?.safeAreaInsets.bottom ?? 0.0)
}
옵셔널 경고창이 뜨지 않게 하려고 위 샘플 코드에서는 if-let과 코알레싱 등을 사용하긴 했지만,
앱에서 UIWindowScene이 없는 경우는 거의 없을 것이기 때문에.. 강제 언래핑을 사용해도 괜찮지 않을까?? 싶다.
'iOS(macOS) > Swift' 카테고리의 다른 글
[iOS/Swift] NavigationController 뒤로가기 버튼 타이틀 수정하기 (0) | 2022.10.27 |
---|---|
[iOS/Swift] Safe Area를 색칠하는 방법 (2) | 2022.09.30 |
[iOS/Xcode 13] Rename - Outlet 변수 이름 수정 방법 (0) | 2022.08.15 |
[iOS/Xcode 13] 시뮬레이터 키보드 보이게 하는 법 (0) | 2022.08.15 |
[Swift/문법] 고차함수 (Higher-order function) (0) | 2022.08.11 |