我想拥有一个ScrollView
,您可以在其中知道用户滚动时内容框架的变化(类似于UIKit didScroll
中的UIScrollView
委托)。
这样,您便可以根据滚动行为执行布局更改。
最佳答案
通过使用“视图首选项”作为在“视图层次结构”中通知上游布局信息的方法,我设法为该问题提供了一个不错的解决方案。
有关“视图首选项”如何工作的非常详细的解释,我建议您通过3 articles series阅读关于主题的kontiki
对于我的解决方案,我实现了两个ViewModifiers
:一个使用锚首选项对视图的布局进行视图更改,第二个允许View
处理其子树上视图框架的更新。
为此,我们首先定义一个Struct
在上游携带可识别的帧信息:
/// Represents the `frame` of an identifiable view as an `Anchor`
struct ViewFrame: Equatable {
/// A given identifier for the View to faciliate processing
/// of frame updates
let viewId : String
/// An `Anchor` representation of the View
let frameAnchor: Anchor<CGRect>
// Conformace to Equatable is required for supporting
// view udpates via `PreferenceKey`
static func == (lhs: ViewFrame, rhs: ViewFrame) -> Bool {
// Since we can currently not compare `Anchor<CGRect>` values
// without a Geometry reader, we return here `false` so that on
// every change on bounds an update is issued.
return false
}
}
并且我们定义了一个符合
Struct
协议的PreferenceKey
来保存视图树的首选项更改:/// A `PreferenceKey` to provide View frame updates in a View tree
struct FramePreferenceKey: PreferenceKey {
typealias Value = [ViewFrame] // The list of view frame changes in a View tree.
static var defaultValue: [ViewFrame] = []
/// When traversing the view tree, Swift UI will use this function to collect all view frame changes.
static func reduce(value: inout [ViewFrame], nextValue: () -> [ViewFrame]) {
value.append(contentsOf: nextValue())
}
}
现在我们可以定义我提到的
ViewModifiers
:在其布局上进行视图报告更改:
这只是使用处理程序向视图添加
transformAnchorPreference
修饰符,该处理程序仅构造具有当前帧ViewFrame
值的Anchor
实例并将其附加到FramePreferenceKey
的当前值:/// Adds an Anchor preference to notify of frame changes
struct ProvideFrameChanges: ViewModifier {
var viewId : String
func body(content: Content) -> some View {
content
.transformAnchorPreference(key: FramePreferenceKey.self, value: .bounds) {
$0.append(ViewFrame(viewId: self.viewId, frameAnchor: $1))
}
}
}
extension View {
/// Adds an Anchor preference to notify of frame changes
/// - Parameter viewId: A `String` identifying the View
func provideFrameChanges(viewId : String) -> some View {
ModifiedContent(content: self, modifier: ProvideFrameChanges(viewId: viewId))
}
}
为视图提供更新处理程序,以在其子树上更改框架:
这会在视图中添加
onPreferenceChange
修饰符,其中框架锚更改列表在视图的坐标空间上转换为框架(CGRect
),并报告为由视图ID键控的框架更新字典:typealias ViewTreeFrameChanges = [String : CGRect]
/// Provides a block to handle internal View tree frame changes
/// for views using the `ProvideFrameChanges` in own coordinate space.
struct HandleViewTreeFrameChanges: ViewModifier {
/// The handler to process Frame changes on this views subtree.
/// `ViewTreeFrameChanges` is a dictionary where keys are string view ids
/// and values are the updated view frame (`CGRect`)
var handler : (ViewTreeFrameChanges)->Void
func body(content: Content) -> some View {
GeometryReader { contentGeometry in
content
.onPreferenceChange(FramePreferenceKey.self) {
self._updateViewTreeLayoutChanges($0, in: contentGeometry)
}
}
}
private func _updateViewTreeLayoutChanges(_ changes : [ViewFrame], in geometry : GeometryProxy) {
let pairs = changes.map({ ($0.viewId, geometry[$0.frameAnchor]) })
handler(Dictionary(uniqueKeysWithValues: pairs))
}
}
extension View {
/// Adds an Anchor preference to notify of frame changes
/// - Parameter viewId: A `String` identifying the View
func handleViewTreeFrameChanges(_ handler : @escaping (ViewTreeFrameChanges)->Void) -> some View {
ModifiedContent(content: self, modifier: HandleViewTreeFrameChanges(handler: handler))
}
}
让我们使用它:
我将通过一个示例来说明用法:
在这里,我将收到
ScrollView
中的Header View框架更改的通知。由于此标题视图位于ScrollView
内容的顶部,因此,报告的帧原点上的帧更改等同于contentOffset
的ScrollView
更改。enum TestEnum : String, CaseIterable, Identifiable {
case one, two, three, four, five, six, seven, eight, nine, ten
var id: String {
rawValue
}
}
struct TestView: View {
private let _listHeaderViewId = "testView_ListHeader"
var body: some View {
ScrollView {
// Header View
Text("This is some Header")
.provideFrameChanges(viewId: self._listHeaderViewId)
// List of test values
ForEach(TestEnum.allCases) {
Text($0.rawValue)
.padding(60)
}
}
.handleViewTreeFrameChanges {
self._updateViewTreeLayoutChanges($0)
}
}
private func _updateViewTreeLayoutChanges(_ changes : ViewTreeFrameChanges) {
print(changes)
}
}
关于ios - 带有内容框架更新功能的SwiftUI ScrollView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58416242/