xcode 快捷列表-快速滚动

ttisahbt  于 2022-12-19  发布在  其他
关注(0)|答案(1)|浏览(104)

我有全屏元素列表。

VStack{
        List {
           ForEach(books, id: \.id) { book in
             Text(book.title)
               .background(Color.yellow) // text background
               .listRowBackground(Color.blue) // cell background
           }
           .frame(height: UIScreen.main.bounds.height)
         }

    }
    .background(Color.red)
    .edgesIgnoringSafeArea(.all)

滚动时有可能在顶部捕捉每个单元格吗?我不知道如何做到这一点。
谢谢大家!

qojgxg4l

qojgxg4l1#

可以使用DragGestureScrollViewReader在SwiftUI中创建捕捉列表。
我们在计算移动列表的速度。

下面是一个完整的示例代码:

struct SampleSnappingListView: View {
enum ScrollDirection {
    case up
    case down
    case none
}
@State var scrollDirection: ScrollDirection = .none

var body: some View {
    VStack {
        ScrollViewReader { reader in
            List {
                ForEach(0...20, id:\.self) { index in
                    ZStack {
                        Color((index % 2 == 0) ? .red : .green)
                        VStack {
                            Text("Index \(index)")
                                .font(.title)
                        }
                        .frame(height: UIScreen.main.bounds.height/2)
                    }
                    .clipShape(Rectangle())
                    .id(index)
                    .simultaneousGesture(
                        DragGesture(minimumDistance: 0.0)
                            .onChanged({ dragValue in
                                let isScrollDown = 0 > dragValue.translation.height
                                self.scrollDirection = isScrollDown ? .down : .up
                            })
                            .onEnded { value in
                                let velocity = CGSize(
                                    width:  value.predictedEndLocation.x - value.location.x,
                                    height: value.predictedEndLocation.y - value.location.y
                                )
                                if abs(velocity.height) > 100 {
                                    withAnimation(.easeOut(duration: 0.5)) {
                                        let next = index + (scrollDirection == .down ? 1 : -1)
                                        reader.scrollTo(next, anchor: .top)
                                    }
                                }
                            }
                    )
                    
                }
                .listRowSeparator(.hidden)
                .listRowBackground(Color.clear)
                .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
            }
            .listStyle(.plain)
            
        }
    }
  }
}

struct SampleSnappingListView_Previews: PreviewProvider {
   static var previews: some View {
      NavigationView {
        SampleSnappingListView()
            .navigationTitle("Snapping list")
            .navigationBarTitleDisplayMode(.inline)
    }
  }
}

相关问题