Skip to content

Instantly share code, notes, and snippets.

@daehn
Last active August 31, 2021 18:58
Show Gist options
  • Save daehn/ea0c4e14d0bf49dd06021cc509b737fd to your computer and use it in GitHub Desktop.
Save daehn/ea0c4e14d0bf49dd06021cc509b737fd to your computer and use it in GitHub Desktop.
SwiftGen Stencil template to create UIColor and UIImage extensions for all asset catalogs.
/// Attention: Changes made to this file will not have any effect and will be reverted
/// when building the project. Please adjust the Stencil template `asset_extensions.stencil` instead.
/// See https://github.com/SwiftGen/SwiftGen#bundled-templates-vs-custom-ones for more information.
import UIKit
// MARK: - Private Helper -
private final class BundleToken {}
private let bundle = Bundle(for: BundleToken.self)
{# Macro to create a static property for a given asset and class type #}
{% macro staticAsset type asset %}
static let {{asset.name|swiftIdentifier:"pretty"|lowerFirstWord|escapeReservedKeywords}} = {{type}}(named: "{{asset.value}}", in: bundle, compatibleWith: nil)!
{% endmacro %}
{# Create an UIColor extension for all color assets in asset catalogs #}
// MARK: - Colors -
extension UIColor {
{% for catalog in catalogs %}
{% for asset in catalog.assets %}
{% if asset.type == "color" %}
{% filter indent:4 %}{% call staticAsset "UIColor" asset %}{% endfilter %}
{% endif %}
{% endfor %}
{% endfor %}
}
{# Create an UIImage extension for all image assets in asset catalogs #}
// MARK: - Images -
extension UIImage {
{% for catalog in catalogs %}
{% for asset in catalog.assets %}
{% if asset.type == "image" %}
{% filter indent:4 %}{% call staticAsset "UIImage" asset %}{% endfilter %}
{% endif %}
{% endfor %}
{% endfor %}
}
@daehn
Copy link
Author

daehn commented Aug 31, 2021

Hey, not sure to be honest, probably best to look at the stencil documentation or look at the templates included with SwiftGen (in case they already handle this).

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