struct CustomTiltePreferenceKey: PreferenceKey {
static var defaultValue: String = ""
static func reduce(value: inout String, nextValue: () -> String) {
value = nextValue()
}
}
extension View {
func customTitle(_ text: String) -> some View {
preference(key: CustomTiltePreferenceKey.self, value: text)
}
}
//内层结构使用preference将值传送到外部
struct SecondaryScreen: View {
let text: String
@State private var newValue: String = ""
var body: some View {
Text(text)
.onAppear(perform: getDataFromDatabase)
.customTitle(newValue)
}
func getDataFromDatabase() {
// download fake data
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
self.newValue = "New Value From DB"
}
}
}
//使用例子
struct PreferenceKeyBootCamp: View {
// MARK: - PROPERTY
@State private var text: String = "Hellow world!"
// MARK: - BODY
var body: some View {
NavigationView {
VStack {
SecondaryScreen(text: text)
.navigationTitle("Navigation Title")
} //: VSTACK
} //: NAVIGATION
.onPreferenceChange(CustomTiltePreferenceKey.self) { value in
self.text = value
}
}
}
- 4、效果图
![请添加图片描述](https://img-blog.csdnimg.cn/6aded77536e245c3896785f255960621.gif)