In Objective-C we can get device width and height by using following code :
CGRect sizeRect = [UIScreen mainScreen].applicationFrame
float width = sizeRect.size.width
float height = sizeRect.size.height
How can do this in with Swift ?
I haven't tried but it should be..
var bounds = UIScreen.main.bounds
var width = bounds.size.width
var height = bounds.size.height
@Houssni 's answer is correct, but since we're talking Swift and this use case will come up often, one could consider extending CGRect
similar to this:
extension CGRect {
var wh: (w: CGFloat, h: CGFloat) {
return (size.width, size.height)
}
}
Then you can use it like:
let (width, height) = UIScreen.mainScreen().applicationFrame.wh
Hooray! :)
Swift 4.2
let screenBounds = UIScreen.main.bounds
let width = screenBounds.width
let height = screenBounds.height
If you want to use it in your code. Here you go.
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
Exactly like this, tested it also.
(Swift 3) Keep in mind that most width and height values will be based on device's current orientation. If you want a consistent value that is not based on rotation and offers results as if you were in a portrait-up rotation, give fixedCoordinateSpace a try:
let screenSize = UIScreen.main.fixedCoordinateSpace.bounds
Since you're looking for the device screen size the simplest way is:
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
来源:https://stackoverflow.com/questions/24084941/how-to-get-device-width-and-height