【问题标题】:SwiftUI scroll to horizontal list itemSwiftUI 滚动到水平列表项
【发布时间】:2021-09-22 06:54:58
【问题描述】:

我可以使用 ScrollViewReader 代理滚动到垂直列表项。

我尝试用水平列表做类似的事情,但它完全搞砸了视图。

任何建议,如何做到这一点?

蒂亚!

   ScrollViewReader { proxy in
        ScrollView(.horizontal, showsIndicators:false) {
            ForEach(0..<items.count) { index in
                Text(items[index].title)
                    .id(index)
                    .onTapGesture {
                        print("tapped \(index)")
                    }
            }
            .onAppear{
                proxy.scrollTo(selectedIndex, anchor: .center)
            }
        }
    }

【问题讨论】:

标签: swiftui


【解决方案1】:

ScrollView 不会因为您指定 .horizontal 滚动而将您的视图排成一行。

您需要在ScrollView 中明确指定HStack/LazyHStack

您可能遇到的另一个问题是滚动位置不准确,可以使用DispatchQueue.main.async修复:

ScrollViewReader { proxy in
    ScrollView(.horizontal, showsIndicators: false) {
        HStack { // or LazyHStack
            ForEach(0..<items.count) { index in
                Text(items[index].title)
                    .id(index)
                    .onTapGesture {
                        print("tapped \(index)")
                    }
            }
        }
        .onAppear {
            DispatchQueue.main.async { 
                proxy.scrollTo(selectedIndex, anchor: .center)
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 2011-04-28
    • 1970-01-01
    • 2021-03-16
    • 2019-01-06
    相关资源
    最近更新 更多