Determine Main Screen Height and Width in Swift

In this tutorial, you’ll learn how to determine the main screen’s height and width in both UIKit and SwiftUI. You need to know this if you want your mobile apps to adapt to different screen sizes and orientations.

If you are interested in learning how to determine device orientation and how to handle device rotation, then read this tutorial: Determine Device Orientation in Swift.

Step 1: Get Main Screen Bounds

Screen bounds represent the rectangle, expressed as a location (x,y) and size (width, height), that defines the area in which the screen content is displayed.

UIKit

In UIKit, you can access the main screen’s bounds using UIScreen.main.bounds. This returns a CGRect object that includes the origin point (0,0) and the dimensions of the screen.

let screenSize: CGRect = UIScreen.main.bounds

SwiftUI

In SwiftUI, you can use the GeometryReader to access the screen bounds indirectly. GeometryReader provides a view that can read its parent’s size and position.

GeometryReader { geometry in
    let screenSize = geometry.size
}

Step 2: Get Screen Width and Height

Once you have the screen bounds, you can easily get the screen width and height by accessing the width and height properties of the bounds rectangle. the code for getting screen width and height is similar to UIKit and SwiftUI.

let screenWidth = screenSize.width
let screenHeight = screenSize.height

Complete Code Example for UIKit

Here’s how you can put it all together in a UIKit application.

import UIKit

class ViewController: UIViewController  {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        let screenSize: CGRect = UIScreen.main.bounds
        let screenWidth = screenSize.width
        let screenHeight = screenSize.height
        print("Screen width = \(screenWidth), screen height = \(screenHeight)")
    }
}

Complete Code Example for SwiftUI

In SwiftUI, you can achieve the same by using a GeometryReader within your view.

import SwiftUI

struct ContentView: View {
    var body: some View {
        GeometryReader { geometry in
            let screenSize = geometry.size
            Text("Screen width = \(screenSize.width), screen height = \(screenSize.height)")
                .font(.title)
                .padding()
        }
    }
}

Determine Main Screen Height and Width

Conclusion

I hope this tutorial was helpful to you.

To learn more about Swift and to find other code examples, check the following page: Swift Code Examples.

Keep coding!

Leave a Reply

Your email address will not be published. Required fields are marked *