滑动时自动滚动到 next/previous 个单元格

AutoScroll to next/previous cell on swipe

我创建了一个水平的 tableView,其中的单元格占据了整个视图控制器。我不想使用默认设置滚动,而是想使用 scrollView.scrollToItem(at: IndexPath 方法滚动到下一个单元格。

意思是,每次用户向右滑动,它会自动滚动到下一个单元格,每次用户向左滑动,它会自动滚动到上一个单元格。每当你滚动一个方向时,它应该自动滚动到下一个或上一个单元格。

我尝试使用 scrollViewDidScroll 委托方法拦截它,但我 运行 遇到了很多问题,它来回自动滚动并出现大量故障。我做错了什么?

var previousOffset: CGFloat = 0.0
var allowHorizontalScroll: Bool = true

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    if (allowHorizontalScroll){
        let offset = scrollView.contentOffset.x
        let diff = previousOffset - offset
        previousOffset = offset

        var currentBoardIndex = scrollView.indexPathForItem(at: CGPoint(x:offset, y:10))?.item
        if currentBoardIndex != nil {
            if diff > 0 {

                //print("scroll left")
                if (currentBoardIndex != 0){
                    currentBoardIndex = currentBoardIndex! - 1
                    allowHorizontalScroll = false
                    scrollView.scrollToItem(at: IndexPath(row: (currentBoardIndex!), section: 0), at: .left, animated: true)
                }

            }else{

                //print("scroll right")
                if (currentBoardIndex != ((boardVCDataSource?.fetchedResultsController.fetchedObjects?.count)! - 1)){
                    currentBoardIndex = currentBoardIndex! + 1
                    allowHorizontalScroll = false
                    scrollView.scrollToItem(at: IndexPath(row: (currentBoardIndex!), section: 0), at: .left, animated: true)
                }
            }
        }
    }
}

Whenever you scroll a direction, it should automatically scroll to the next or previous cell.

为什么不丢弃所有这些代码,而是将滚动视图的 isPagingEnabled 设置为 true?分页滚动视图会按照您的描述进行操作,自动