GitHub Twitter: @lukeeep_

SFSymbolsMacro

这个 Swift 宏提供了一种简便的方式,使在 Swift 中使用 SF Symbols 更具或多或少的“类型安全”

安装

Xcode

  1. 点击 文件 > 添加包依赖项
  2. 将以下链接粘贴到右上角的搜索框中
    https://github.com/lukepistrol/SFSymbolsMacro.git
    

Swift Package Manager

Package.swift

dependencies: [
    .package(url: "https://github.com/lukepistrol/SFSymbolsMacro.git", from: "0.1.0")
]

然后将依赖项添加到你的 target 中。

用法

简单地创建一个 enum,它将包含你项目的所有 SF Symbols

enum Symbols: String {
    case circle
    case circleFill = "circle.fill"
    case shareIcon = "square.and.arrow.up"
    case globe
}

然后简单地导入 SFSymbolsMacro 并在 enum 上添加 @SFSymbol 宏注解

import SFSymbolsMacro
import SwiftUI

@SFSymbol
enum Symbols: String { ... }

然后,宏将验证每个 case,并且展开后的宏看起来像这样

enum Symbols: String {
    case circle
    case circleFill = "circle.fill"
    case shareIcon = "square.and.arrow.up"
    case globe

    var image: Image {
        Image(systemName: self.rawValue)
    }
    var name: String {
        self.rawValue
    }
    #if canImport(UIKit)
    func uiImage(configuration: UIImage.Configuration? = nil) -> UIImage {
        UIImage(systemName: self.rawValue, withConfiguration: configuration)!
    }
    #else
    func nsImage(accessibilityDescription: String? = nil) -> NSImage {
        return NSImage(systemSymbolName: self.rawValue, accessibilityDescription: accessibilityDescription)!
    }
    #endif
    func callAsFunction() -> String {
        return self.rawValue
    }
}

在你的代码中,你可以调用一个 symbol

var body: some View {
    VStack {
        Symbols.circleFill.image
        Label("Globe", systemImage: Symbols.globe.name)
        // the above can also be written as
        Label("Globe", systemImage: Symbols.globe())
    }
}

如果提供的原始值不是有效的 SF Symbol,Xcode 将在有问题的 enum-case 处显示编译错误

explicit raw value

inferred raw value

贡献

如果您对如何进一步发展它有任何想法,我很乐意在 issue 中讨论。


Buy Me A Coffee