Joe Huang
Joe Huang

Reputation: 6550

In Swift, how to determine the physical size of a device screen?

I am adding views programatically. For example, I have a scrollView as a top-bar menu, I set its height to 60. (I am already using auto layout for placing these views)

This top-bar menu looks alright visually in an iPad. However, in an iPhone, it's kind of occupying too much space. Therefore, I am thinking to change the height to 45 for an iPhone.

What's the way to get the physical size of the screen? (not screen resolution) So I can make the height proportional to the physical size?

Upvotes: 5

Views: 6551

Answers (5)

S_Vovchyna
S_Vovchyna

Reputation: 51

You can always use:

UIScreen.main.bounds.width and UIScreen.main.bounds.height

It works from any scope. For the brevity's sake you can have extensions like

extension UIScreen {
    static var screenHeight: CGFloat {
        UIScreen.main.bounds.height
    }
    static var screenWidth: CGFloat {
        UIScreen.main.bounds.width
    }
}

and use it like this:

UIScreen.screenWidth
UIScreen.screenHeight

Upvotes: 0

rkyr
rkyr

Reputation: 3241

You can get this information accessing UIScreen singleton.

To get size use UIScreen.main.nativeBounds. Also you can get scale coefficient of screen UIScreen.main.nativeScale.

Upvotes: 6

Krish Wadhwana
Krish Wadhwana

Reputation: 1544

Use view.frame.size.height and view.frame.size.width to determine the size of different screen sizes. This will work inside functions only.

Upvotes: 0

MazzaMan
MazzaMan

Reputation: 123

This code should adjust your scroll view to the size of the users screen.

self.view.frame.size.height and self.view.frame.size.width

Also, make sure that your constraints are all good.

Upvotes: 0

Fred Faust
Fred Faust

Reputation: 6790

You may want to consider working with the frame property of the view of the current view controller.

self.view.frame.size.height and self.view.frame.size.width

You can make your other views proportional to those dimensions or based on their values, etc.

Upvotes: 4

Related Questions