【发布时间】:2021-08-09 06:42:11
【问题描述】:
使用this code 作为参考。
如果将代码注释掉,内容为空,然后运行,也会出现同样的行为。
struct SizePreferenceKey: PreferenceKey {
typealias Value = CGSize
static var defaultValue: Value = .zero
static func reduce(value _: inout Value, nextValue: () -> Value) {
// _ = nextValue() <-- comment out
}
}
我对@987654322@ 尝试了同样的操作,效果很好。
struct ViewOffsetKey: PreferenceKey {
typealias Value = CGFloat
static var defaultValue = CGFloat.zero
static func reduce(value: inout Value, nextValue: () -> Value) {
// value += nextValue() <-- comment out
}
}
我必须将它写到conformprotocol,但即使内容为空,它似乎也可以工作。为什么是这样?我什么时候需要内容?
换句话说,onPreferenceChange 似乎在不更新value 的情况下工作正常。这是为什么呢?
【问题讨论】:
-
reduce仅在您使用同一个键有多个视图时才相关。在您引用的两个示例中都没有发生这种情况。答案可能会在确实发生这种情况的情况下使用,这可能是答案包括reduce的实现。