Skip to content

Instantly share code, notes, and snippets.

import UIKit
// MARK: Image helpers
extension UIImage {
struct Constants {
static let defaultTraits = [UITraitCollection(userInterfaceStyle: .dark),
UITraitCollection(userInterfaceStyle: .light)]
}
combinedImages.imageAsset?.image(with: UITraitCollection(userInterfaceStyle: .light))
combinedImages.imageAsset?.image(with: UITraitCollection(userInterfaceStyle: .dark))
// Create an asset
let set = UIImageAsset()
// Define traits to be specific for the images
let darkTraits = UITraitCollection(traitsFrom: [UITraitCollection(userInterfaceStyle: .dark),
UITraitCollection(displayScale: someDarkImage.scale)])
let lightTraits = UITraitCollection(traitsFrom: [UITraitCollection(userInterfaceStyle: .light),
UITraitCollection(displayScale: someLightImage.scale)])
// Register the images alongside the traits
let someImage = UIImage.buttonBackground(color: backgroundColor,
borderColor: borderColour,
borderWidth: 2,
cornerRadius: 8)
extension UIImage {
static func buttonBackground(color: UIColor,
borderColor: UIColor,
borderWidth: CGFloat,
cornerRadius: CGFloat) -> UIImage {
let width = max(2, cornerRadius * 2)
let size = CGSize(width: width, height: width)
return UIGraphicsImageRenderer(size: size).image { context in
color.setFill()
let backgroundColor = UIColor {
$0.userInterfaceStyle == .dark ?
UIColor(red: 10.0 / 255, green: 40.0 / 255, blue: 58.0 / 255, alpha: 1) :
UIColor(red: 183.0 / 255, green: 228.0 / 255, blue: 255.0 / 255, alpha: 1)
}
// Or in short:
let borderColour = UIColor {
$0.userInterfaceStyle == .dark ?
UIColor(red: 197.0 / 255, green: 197.0 / 255, blue: 197.0 / 255, alpha: 1) :
extension UIButton {
func apply(style: ButtonStyle) {
backgroundColor = nil
titleLabel?.font = style.font
contentEdgeInsets = style.insets
setTitleColor(style.enabled.foreground, for: .normal)
setTitleColor(style.highlighted.foreground, for: .highlighted)
setTitleColor(style.disabled.foreground, for: .disabled)
private struct Palette {
static let foreground = UIColor(named: "color/foreground")!
}
struct ComponentStyle {
struct Button {
private static let defaultInsets = UIEdgeInsets(top: 12, left: 16, bottom: 12, right: 16)
private static let defaultFont = UIFont.preferredFont(forTextStyle: .body)
static let primary =
// Note: Idealy, these are generated using SwiftGen
private struct Palette {
static let foreground = UIColor(named: "color/foreground")!
}
private struct Fonts {
static let body = UIFont.preferredFont(forTextStyle: .body)
}
extension ButtonStyle {
func apply(to button: UIButton) {
button.backgroundColor = nil
button.titleLabel?.font = font
button.contentEdgeInsets = insets
button.setTitleColor(enabled.foreground, for: .normal)
button.setTitleColor(highlighted.foreground, for: .highlighted)
button.setTitleColor(disabled.foreground, for: .disabled)