Get Up & Code, MacKin Talk

iOS Device Screen Size Height, Width 값 얻기(feat. UIScreen.main) 본문

IOS

iOS Device Screen Size Height, Width 값 얻기(feat. UIScreen.main)

맥킨 2023. 3. 26. 13:15

목차

1) iOS ~16.0

2) iOS 16.0 < (version) 

3) 기타 참고


1) iOS ~16.0

 

일반적으로 iOS Device의 Screen Size를 얻기 위해서

다음과 같은 로직을 많이 써왔다.

UIScreen.main.bounds.size.height
UIScreen.main.bounds.size.width

 

코드 작업 중 Xcode IDE에 의해 main이 deprecated 될 거라는 경고문을 안내받았다.

Xcode IDE 14.1
https://developer.apple.com/documentation/uikit/uiscreen/1617815-main

경고문에 안내하듯

Context에 의해 찾아진 UIScreen 인스턴스로 대체하라는 방식대로 코드를 작성하라고 안내하고 있다.

ex) view.window.windowScene.screen

 

 

2) iOS 16.0 < (version) 

StackOver Flow에서 관련된 질의글을 찾았고, 두 개의 답변이 작성된 답변은 다음과 같았다.

 

1.

let screenSize = self.view.window?.windowScene?.screen.bounds.size

2.

extension UIViewController {
  func screen() -> UIScreen? {
    var parent = self.parent
    var lastParent = parent
    
    while parent != nil {
      lastParent = parent
      parent = parent!.parent
    }
    
    return lastParent?.view.window?.windowScene?.screen
  }
}

self.screen().bounds.size.height
self.screen().bounds.size.width

공통적으로 두 가지 예시 코드 모두 UIScreen.main을 UIScreen instance로 대체하고 있다.

코드를 쭉 읽어보면 두 방식 모두 window 객체의 windowScene을 통해 UIScreen instance에 접근한다.

 

물론 정말 예외적인 상황을 제외하고, 위 두 예시 코드 중 어떤 방식을 사용하더라도 Device의 너비, 높이값을 구할 수 있을 것으로 보인다.

 

다만 Apple이 가이드한 방식대로


find the UIScreen instance through context Instead

라는 말을 이해하기 위해서는 UIScreen이라는 것이 무엇인지 명확하게 알고 사용할 필요가 있다.


관련하여 도움을 받을 수 있는 자료의 링크들을 공유한다.

 

https://developer.apple.com/documentation/uikit/uiwindow

윈도우란? https://woozzang.tistory.com/143

view programming guide for iOS https://developer.apple.com/library/archive/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/Introduction/Introduction.html#//apple_ref/doc/uid/TP40009503-CH1-SW2

 

 

 

 

ref.

https://developer.apple.com/documentation/uikit/uiscreen

https://developer.apple.com/documentation/uikit/uiwindow

https://stackoverflow.com/questions/74458971/correct-way-to-get-the-screen-size-on-ios-after-uiscreen-main-deprecation