温馨提示:本文最后更新于
2024-07-10 10:02:56
,某些文章具有时效性,若有错误或已失效,请在下方留言。环境键的自定义需要两个必要步骤和一个可选步骤:
- 实现⼀个⾃定义的 EnvironmentKey。
- 在 EnvironmentValues 上添加扩展,并提供⼀个属性,让我们能在环境中获取和设置该值。
- (可选) 在 View 上提供⼀个辅助⽅法,
例如,自定义角标颜色的示例
第⼀步,我们先来创建⼀个⾃定义的环境键。环境键并不是⼀个值,⽽是使⽤类型来定义的。我们将创建⼀个空的 enum 类型 (或者也可以使⽤ struct 类型),并让它满⾜ EnvironmentKey 协议:
enum BadgeColorKey: EnvironmentKey {
static var defaultValue: Color = .blue
}
EnvironmentKey 协议要求我们实现静态的 defaultValue 属性。因为我们使⽤ Color 作为它的类型,编译器将知道这个键所对应的值始终会是 Color 类型。
第⼆步,我们需要向 EnvironmentValues 结构体添加⼀个计算属性。我们在环境中进⾏读写时需要⼀个键路径,本例中,我们使⽤ badgeColor 这个名字:
extension EnvironmentValues {
var badgeColor: Color {
get { self[BadgeColorKey.self] }
set { self[BadgeColorKey.self] = newValue }
}
}
最后,我们添加⼀个辅助⽅法来设置颜⾊:
extension View {
func badgeColor(_ color: Color) -> some View {
environment(\.badgeColor, color)
}
}
想要读取⻆标颜⾊,我们可以在 Badge 视图修饰符⾥使⽤ @Environment 属性包装器:
struct Badge: ViewModifier {
@Environment(\.badgeColor) private var badgeColor
func body(content: Content) -> some View {
content
.font(.caption)
.foregroundStyle(.white)
.padding(.horizontal, 5)
.padding(.vertical, 2)
.background(
Capsule(style: .continuous)
.fill(badgeColor)
)
}
}
现在可以使用环境来修改角标样式
struct ContentView: View {
var body: some View {
VStack {
Text(3000, format: .number)
.modifier(Badge())
Text("Test")
.modifier(Badge())
}
.badgeColor(.orange)
}
}

© 版权声明
THE END
暂无评论内容