Search code examples
iosxcodemacostvoswatchos

Getting device aspect ratio in Xcode programmatically


I'm making a universal game across all apple platforms. The problem is there are lots of aspect ratios, and with the growing numbers of devices, it becomes a hassle. I've tried the following:

var deviceAspectRatio: CGFloat? {
#if os(iOS)
    if UIDevice.current.model.contains("iPhone") {
        return 16/9
    } else if UIDevice.current.model.contains("iPad") {
        return 4/3
    }
#elseif os(tvOS)
    return 16/9 //There might be other aspect ratios also
#elseif os(watchOS)
    return 1
#elseif os(macOS)
    //figure out aspect ratio
#else
    return nil
#endif
}

But even with this, Xcode gives me an error:

Missing return in a function expected to return 'CGFloat?'


Solution

  • The trick on macOS is that there might be more than one screen, so if this is the case, you'll have to decide which one you're interested in. However, if you settle on a screen, you can just get the frame from NSScreen.frame and divide the width by the height.

    This code will get the aspect ratio for the screen a given window is on:

    guard let frame = someWindow.screen?.frame else { return nil }
    let aspectRatio = NSWidth(frame) / NSHeight(frame)
    

    Also, you should probably be doing something similar with UIScreen on iOS instead of hard-coding the values there. Apple may someday release a new device with some other aspect ratio your app doesn't anticipate.