|
| 1 | +// |
| 2 | +// SystemImage.swift |
| 3 | +// YCoreUI |
| 4 | +// |
| 5 | +// Created by Mark Pospesel on 3/8/23. |
| 6 | +// Copyright © 2023 Y Media Labs. All rights reserved. |
| 7 | +// |
| 8 | + |
| 9 | +import UIKit |
| 10 | + |
| 11 | +/// Any string corresponding to a system image (SF Symbols). |
| 12 | +/// |
| 13 | +/// All properties and functions have default implementations. At a minimum just have your string-based enum conform |
| 14 | +/// to `SystemImage`. The raw value of the enum should match a sytem image name (e.g. `checkmark.seal`). |
| 15 | +public protocol SystemImage: RawRepresentable where RawValue == String { |
| 16 | + /// Fallback image to use in case a system image cannot be loaded. |
| 17 | + /// (default is a 16 x 16 square filled with `.systemPink`) |
| 18 | + static var fallbackImage: UIImage { get } |
| 19 | + |
| 20 | + /// A system image for this name value. |
| 21 | + /// |
| 22 | + /// Default implementation calls `loadImage` and nil-coalesces to `fallbackImage`. |
| 23 | + var image: UIImage { get } |
| 24 | + |
| 25 | + /// Loads the named system image. |
| 26 | + /// - Returns: The named system image or else `nil` if the system image cannot be loaded. |
| 27 | + func loadImage() -> UIImage? |
| 28 | +} |
| 29 | + |
| 30 | +extension SystemImage { |
| 31 | + /// Fallback image to use in case a system image cannot be loaded. |
| 32 | + /// (default is a 16 x 16 square filled with `.systemPink`) |
| 33 | + public static var fallbackImage: UIImage { |
| 34 | + let renderer = UIGraphicsImageRenderer(size: CGSize(width: 16, height: 16)) |
| 35 | + let image = renderer.image { ctx in |
| 36 | + UIColor.systemPink.setFill() |
| 37 | + ctx.fill(CGRect(origin: .zero, size: renderer.format.bounds.size)) |
| 38 | + } |
| 39 | + return image |
| 40 | + } |
| 41 | + |
| 42 | + /// Loads the named system image. |
| 43 | + /// |
| 44 | + /// Default implementation uses `UIImage(systemName:)` passing in the associated `rawValue`. |
| 45 | + /// - Returns: The named system image or else `nil` if the system image cannot be loaded. |
| 46 | + public func loadImage() -> UIImage? { |
| 47 | + UIImage(systemName: rawValue) |
| 48 | + } |
| 49 | + |
| 50 | + /// A system image for this name value. |
| 51 | + /// |
| 52 | + /// Default implementation calls `loadImage` and nil-coalesces to `fallbackImage`. |
| 53 | + public var image: UIImage { loadImage() ?? Self.fallbackImage } |
| 54 | +} |
0 commit comments