EnvironmentKey(环境中定义自定义值的协议)
定义 EnvironmentKey
EnvironmentKey示例
import SwiftUI
// 自定义一个环境键
struct CustomTitleKey: EnvironmentKey {
static let defaultValue: String = "默认标题"
}
// 扩展 EnvironmentValues 来添加自定义键
extension EnvironmentValues {
var customTitle: String {
get { self[CustomTitleKey.self] }
set { self[CustomTitleKey.self] = newValue }
}
}
// 使用自定义的 EnvironmentKey
struct ContentView: View {
@Environment(\.customTitle) var title
var body: some View {
Text(title)
}
}
// 设置环境值
struct ParentView: View {
var body: some View {
ContentView()
.environment(\.customTitle, "自定义标题")
}
}关键点
Last updated