Skip to content

Instantly share code, notes, and snippets.

@manmal
Created May 12, 2021 08:07
Show Gist options
  • Save manmal/97247dcea0bdcee92d935d926037ecac to your computer and use it in GitHub Desktop.
Save manmal/97247dcea0bdcee92d935d926037ecac to your computer and use it in GitHub Desktop.
UIImage+LaunchImage
import UIKit
extension UIImage {
/// Available launch images (as of 12 May 2021):
/// [email protected]: 750x1334
/// [email protected]: 828x1792
/// [email protected]: 1242x2208
/// [email protected]: 1125x2436
/// [email protected]: 1242x2688
static var launchImage: UIImage {
let images: [(height: CGFloat, name: String)] = [
(1334, "[email protected]"),
(1792, "[email protected]"),
(2208, "[email protected]"),
(2436, "[email protected]")
]
let image = images
.first { $0.height <= UIScreen.main.nativeBounds.height }
.map(\.name)
.map(UIImage.init(named:))
return (image ?? UIImage(named: "[email protected]"))!
}
}
@marcpalmer
Copy link

marcpalmer commented May 12, 2021

Here's a further suggestion, not sure if it's better:

extension UIImage {
    /// Available launch images (as of 12 May 2021):
    /// [email protected]: 750x1334
    /// [email protected]: 828x1792
    /// [email protected]: 1242x2208
    /// [email protected]: 1125x2436
    /// [email protected]: 1242x2688
    static var launchImage: UIImage {
        let images: [(height: CGFloat, name: String)] = [
            (1334, "[email protected]"),
            (1792, "[email protected]"),
            (2208, "[email protected]"),
            (2436, "[email protected]"),
            (.greatestFiniteMagnitude, "[email protected]") // The default if none match
        ]
        let image = images
            .first(where: { $0.height <= UIScreen.main.nativeBounds.height })
            .map(\.name)
            .flatMap(UIImage.init(named:))
        return image!
    }
}

The flatMap is required because the name is Optional, and then can be mapped to an UIImage?? and the flatMap can flatten that to a single level of optionality (I had to look that up)

@marcpalmer
Copy link

Changing .first(where: { $0.height <= UIScreen.main.nativeBounds.height }) to .first(where: { $0.height >= UIScreen.main.nativeBounds.height }) should get you the correct logic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment