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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With