IT TIP

장치 너비와 높이를 얻는 방법은 무엇입니까?

itqueen 2020. 11. 25. 21:47
반응형

장치 너비와 높이를 얻는 방법은 무엇입니까?


Objective-C에서는 다음 코드를 사용하여 장치 너비와 높이를 얻을 수 있습니다.

CGRect sizeRect = [UIScreen mainScreen].applicationFrame
float width = sizeRect.size.width
float height = sizeRect.size.height

Swift로 어떻게 할 수 있습니까?


시도해 보지 않았지만 그래야하는데 ..

var bounds = UIScreen.main.bounds
var width = bounds.size.width
var height = bounds.size.height

스위프트 4.2

let screenBounds = UIScreen.main.bounds
let width = screenBounds.width
let height = screenBounds.height

@Houssni의 대답은 정확하지만 Swift에 대해 이야기하고 있고이 사용 사례가 자주 등장 CGRect하므로 다음과 유사한 확장을 고려할 수 있습니다 .

extension CGRect {
    var wh: (w: CGFloat, h: CGFloat) {
        return (size.width, size.height)
    }
}

그런 다음 다음과 같이 사용할 수 있습니다.

let (width, height) = UIScreen.mainScreen().applicationFrame.wh

만세! :)


코드에서 사용하려는 경우. 여기 있습니다.

func iPhoneScreenSizes(){
    let bounds = UIScreen.mainScreen().bounds
    let height = bounds.size.height

    switch height {
    case 480.0:
        print("iPhone 3,4")
    case 568.0:
        print("iPhone 5")
    case 667.0:
        print("iPhone 6")
    case 736.0:
        print("iPhone 6+")

    default:
        print("not an iPhone")

    }


}

var sizeRect = UIScreen.mainScreen().applicationFrame
var width    = sizeRect.size.width
var height   = sizeRect.size.height

정확히 이와 같이 테스트했습니다.


(Swift 3) 대부분의 너비 및 높이 값은 기기의 현재 방향을 기준으로합니다. 회전을 기반으로하지 않고 세로 위로 회전 한 것처럼 결과를 제공하는 일관된 값을 원하면 fixedCoordinateSpace 를 시도해보십시오.

let screenSize = UIScreen.main.fixedCoordinateSpace.bounds

장치 화면 크기를 찾고 있으므로 가장 간단한 방법은 다음과 같습니다.

let screenSize = UIScreen.mainScreen().bounds.size
let width = screenSize.width
let height = screenSize.height

While @Adam Smaka's answer was close, in Swift 3 it is the following:

let screenBounds = UIScreen.main.bounds
let width = screenBounds.width
let height = screenBounds.height

A UIScreen object defines the properties associated with a hardware-based display. iOS devices have a main screen and zero or more attached screens. Each screen object defines the bounds rectangle for the associated display and other interesting properties

Apple Doc URL :

https://developer.apple.com/reference/uikit/uiwindow/1621597-screen

To get Height/width of ur user's device with swift 3.0

let screenHeight = UIScreen.main.bounds.height
let screenWidth = UIScreen.main.bounds.width

In Swift 4 I had to use NSScreen.main?.deviceDescription

let deviceDescription = NSScreen.main?.deviceDescription          
let screenSize = deviceDescription![.size]
let screenHeight = (screenSize as! NSSize).height

참고URL : https://stackoverflow.com/questions/24084941/how-to-get-device-width-and-height

반응형