SwiftUI可刷新适用于所有滚动视图



我有一个包含List的结构,在该列表中还有一些其他结构Views。其中一些结构包含水平滚动视图。当我分配给List.refreshable时,该修饰符将应用于该列表中的所有滚动视图。所以所有的水平滚动视图都有垂直的可刷新属性,这不是我想要的。关于如何处理这个问题,有什么想法吗?谢谢

refreshable修饰符在环境中放置一个可刷新的操作。如果它被清除,它应该会阻止子滚动视图拾取它。这是一种纯粹的SwiftUI方法。它被封装在一个方便的修饰符中,但所需要的只是从环境中清除刷新键。.environment(EnvironmentValues.refresh as! WritableKeyPath<EnvironmentValues, RefreshAction?>, nil)

public struct RefreshableBlocker: ViewModifier {
public func body(content: Content) -> some View {
if let refreshKeyPath = EnvironmentValues.refresh as? WritableKeyPath<EnvironmentValues, RefreshAction?> {
content.environment(refreshKeyPath, nil)
} else {
content
}
}
}
public extension View {
func blockPullToRefresh() -> some View {
self.modifier(RefreshableBlocker())
}
}

只需将其放在视图层次结构中子滚动视图的上方。在下面的示例中,您应该能够将List切换为ScrollView。

ScrollView {
LazyVStack(spacing: 12) {
ForEach(items, id: .self) { item in
ItemCell(data: item).blockPullToRefresh()
}
}
}

最新更新