SwiftUI 的实用宏库。
使用此软件包需要 Swift 5.9 或更高版本。
添加依赖项
dependencies: [
.package(url: "https://github.com/Wouter01/SwiftUI-Macros.git", from: "1.0.0")
]
将依赖项添加到你的目标 (target)
.target(
name: "MyTarget",
dependencies: [.product(name: "SwiftUIMacros", package: "SwiftUI-Macros")]
)
为了更容易地创建新的环境键 (environment key),提供了两个宏
将此宏应用于 EnvironmentValues
扩展中的一个变量,以将其添加到环境中。 赋值是默认值,并且是必需的,除非类型是 Optional。 类型可以由其值推断出来,就像在普通的 Swift 代码中一样。
import SwiftUIMacros
extension EnvironmentValues {
@EnvironmentKey
var alignment: Alignment = .center
}
// Expands to
extension EnvironmentValues {
var alignment: Alignment {
get {
self[EnvironmentKey_alignment.self]
}
set {
self[EnvironmentKey_alignment.self] = newValue
}
}
private struct EnvironmentKey_alignment: EnvironmentKey {
static let defaultValue: Alignment = .center
}
}
将此宏应用于 EnvironmentValues
扩展,以便将 EnviromentKey
宏添加到扩展中的每个变量。
import SwiftUIMacros
@EnvironmentValues
extension EnvironmentValues {
var alignment: Alignment = .center
var secondaryFont: Font?
var gridLines = 0
}
// Expands to
extension EnvironmentValues {
@EnvironmentKey
var alignment: Alignment = .center
@EnvironmentKey
var secondaryFont: Font?
@EnvironmentKey
var gridLines = 0
}
为了更容易地创建新的 focusedValue 键,提供了两个宏
将此宏应用于 FocusedValues
扩展中的一个变量,以将其添加到聚焦值 (focused values) 中。
import SwiftUIMacros
extension FocusedValues {
@FocusedValueKey
var enabled: Bool?
}
// Expands to
extension FocusedValues {
@FocusedValueKey
var enabled: Bool? {
get {
self [FocusedValueKey_enabled.self]
}
set {
self [FocusedValueKey_enabled.self] = newValue
}
}
private struct FocusedValueKey_enabled: FocusedValueKey {
typealias Value = Bool
}
}
将此宏应用于 FocusedValues
扩展,以便将 FocusedValueKey
宏添加到扩展中的每个变量。
import SwiftUIMacros
@FocusedValues
extension FocusedValues {
var showCompletions: Binding<Bool>?
var value: Int?
}
// Expands to
extension FocusedValues {
@FocusedValueKey
var showCompletions: Binding<Bool>?
@FocusedValueKey
var value: Int?
}