ios - 单击列表项时滚动到 SwiftUI 中的正确位置

标签 ios swift swiftui

我有一个 SwiftUI ForEach 循环,其中包含单击时展开的 View 。类似于下面显示的 View 。

struct ExpandingView: View {
    
    @State var isExpanded = false
    
    var body: some View {
        VStack {
            Text("Hello!")
            if isExpanded {
                Text("World")
            }
        }
        .onTapGesture {
            withAnimation {
                isExpanded.toggle()
            }
        }
    }
}

理论上,我可以在特定位置使用 ScrollViewReaderscrollTo

ScrollViewReader { view in
    ScrollView {
        ForEach(0...100, id: \.self) { id in
             ExpandingView()
                 .id(id)
                 .padding()                        
        }
    }
}

但是,在实践中,我不确定如何从 View 中获取 id (因为 onTapGesture 位于 View 中)并将其向上传播一级.

另一个选项是在 ForEach 循环中使用 onTapGesture,但我不确定如何切换 isExpanded 标志以获得正确的 View 。

最佳答案

您可以将 ScrollViewProxy 传递给行 View ,然后您现在就可以滚动了。

struct ExpandingView: View {
    
    @State var isExpanded = false
    var id: Int
    var proxy: ScrollViewProxy
    var body: some View {
        VStack {
            Text("Hello!")
            if isExpanded {
                Text("World")
            }
        }
        .onTapGesture {
            withAnimation {
                isExpanded.toggle()
                proxy.scrollTo(id, anchor: .center)
            }
        }
    }
}

struct TestScrollView: View {
    var body: some View {
        ScrollViewReader { view in
            ScrollView {
                ForEach(0...100, id: \.self) { id in
                    ExpandingView(id: id, proxy: view)
                        .id(id)
                        .padding()
                }
            }
        }
    }
}

enter image description here

关于ios - 单击列表项时滚动到 SwiftUI 中的正确位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68142290/

相关文章:

swiftui - 如何在 SwiftUI 中创建清晰背景的 Button

ios - 有没有办法在没有代码的情况下制作 cocoa pod ,只是 repo 中已经编译的.framework?

ios - Realm 模型的关系 - Swift

swift - XCode 预览错误 : "Replaced Accessor for ' keyWindow'"

swift - 如何访问 SwiftUI Canvas 中的像素数据

ios - View 更新期间我正在修改什么状态?

macos - 如何在 SwiftUI、macOS 中打开另一个窗口?

ios - watchOS 2 - 如何随机选择 UIButtons

ios - 如何在 xcode 中创建按钮数组?

ios - 警告 : Attempt to present ViewController on TabBarController whose view is not in the window hierarchy