SFSymbols

SFSymbols 提供了一种类型安全且符合 Swift 习惯的方式来访问 Apple 的 SFSymbol 库。当使用字符串来标记所有内容时,记住所有正确的符号名称变得很困难。此枚举提供了一个简单的方法,可以使用类型安全的接口与 SwiftUI、UIKit 和 AppKit 中的 SFSymbols 交互。

安装

将以下 URL 添加到 Swift Package Manager

https://github.com/ActuallyTaylor/SFSymbols

基本用法

import SwiftUI
import SFSymbols // Import SFSymbols

Image(.sparkles) // Boom 💥, it is that simple.

自定义图片

import SwiftUI
import SFSymbols

Image(.custom("spaceship")) // Will use a custom symbol file located in your assets folder!

高级用法

SwiftUI

图片

默认的 Image 初始化器被自定义的符号初始化器取代。

Image(.hammer)

按钮

已经为按钮添加了两个新的初始化器,允许您使用 SFSymbol 标签自动初始化它们,从而减少视图中的代码量。

// Basic Button initializer 
Button(.fireplace_fill) {
    print("Sit by the fireplace with me!")
}

// Button initializer with a role
Button(.xmark_app_fill, role: .cancel) {
    print("Goodbye!")
}

菜单

已经为菜单添加了两个新的初始化器,允许您使用 SFSymbol 图片标签自动创建它们。

// Basic menu initializer
Menu(.command) {
    Button("Hello World!") {
        print("Hello World!")
    }
}

// Menu initializer with a primary action
Menu(.command) {
    Button("Hello World!") {
        print("Hello World!")
    }
} primaryAction: {
    print("Hello World!")  
}

标签

标签已经添加了两个初始化器,允许您使用 SFSymbol 创建它们。

// Just a string
Label("Hello World", symbol: .figure_wave)

// Localized string key
Label(LocalizedStringKey("hello.world"), symbol: .figure_wave)

UIKit

UIImage

UIImages 已经被赋予了一组初始化器,允许您直接使用 SFSymbols

UIImage(.sparkles)
UIImage(.sparkles, withConfiguration: /* some UIImage Configuration */)
UIImage(.sparkles, compatibleWith: .current)

UIButton

UIButtons 已经被赋予了一个系统按钮初始化器,以及一种将图片直接设置为 SFSymbol 而不需要创建 UIImage 的方法。

// Create a System Button with an SFSymbol
UIButton.systemButton(with: .figure_wave, target: self, action: /* any selector */)

// Set an image for a certain state
UIButton.setImage(.figure_wave, for: .normal)

DisplayRepresentation.Image

DisplayRepresentation 图片已经被赋予了初始化器。 这些仅在您同时导入 UIKit 和 AppIntents 时可用。

DisplayRepresentation.Image(.sparkles, isTemplate: false)
DisplayRepresentation.Image(.sparkles, tintColor: .red, symbolConfiguration: /* some symbol configuration */)

UIApplicationShortcutIcon

UIApplicationShortcutIcon 已经被赋予了一个初始化器,因此可以使用 SFSymbol 创建它们。

UIApplicationShortcutIcon(.sparkles)

AppKit

NSImage

NSImages 已经被赋予了一个初始化器,允许您使用 SFSymbol 创建它们。

NSImage(.sparkles, variableValue: 1.0)

NSButton

NSButtons 已经被赋予了一个初始化器,允许您使用 SFSymbol 初始化它们。 此初始化器允许您设置按钮以自动使用具有给定变量值的 SFSymbol。

NSButton(.sparkles, variableValue: 1.0, target: self, action: /* some selector */)