Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI get Screen size in multiplateform

Tags:

ios

swiftui

Actually, i used in my ContentView.swift file

UIScreen.main.bounds.size.width 

to get width screen's size. Unfortunatelly, i can't used this with an MacOS target because it need NSScreen

NSScreen.main.bounds.size.width

Is there any generic Screen to get the screen size?

like image 846
Kevin ABRIOUX Avatar asked Aug 28 '19 16:08

Kevin ABRIOUX


2 Answers

What I did, to solve this is to create a class with platform conditional.

class SGConvenience{
    #if os(watchOS)
    static var deviceWidth:CGFloat = WKInterfaceDevice.current().screenBounds.size.width
    #elseif os(iOS)
    static var deviceWidth:CGFloat = UIScreen.main.bounds.size.width
    #elseif os(macOS)
    static var deviceWidth:CGFloat? = NSScreen.main?.visibleFrame.size.width // You could implement this to force a CGFloat and get the full device screen size width regardless of the window size with .frame.size.width
    #endif
}

Then I simply call SGConvenience.deviceWidth when needed

like image 168
Fabrice Leyne Avatar answered Oct 12 '22 01:10

Fabrice Leyne


i prefer the extension version:

// MARK UIScreen+size.swift

import UIKit

extension UIScreen
{
#if os(watchOS)
    static let screenSize = WKInterfaceDevice.current().screenBounds.size
    static let screenWidth = screenSize.width
    static let screenHeight = screenSize.height
#elseif os(iOS) || os(tvOS)
    static let screenSize = UIScreen.main.nativeBounds.size
    static let screenWidth = screenSize.width
    static let screenHeight = screenSize.height
#elseif os(macOS)
    static let screenSize = NSScreen.main?.visibleFrame.size
    static let screenWidth = screenSize.width
    static let screenHeight = screenSize.height
#endif
    static let middleOfScreen = CGPoint(x: screenWidth / 2, y: screenHeight / 2)
}

and use it like this:

let screenWidth = UIScreen.screenWidth
let middlePointY = UIScreen.middleOfScreen.y
like image 24
Shaybc Avatar answered Oct 12 '22 01:10

Shaybc