Ios 滑动时自动滚动到下一个/上一个单元格

Ios 滑动时自动滚动到下一个/上一个单元格,ios,scrollview,Ios,Scrollview,我创建了一个水平的tableView,其中的单元格占据了整个视图控制器。我希望使用scrollView.scrollToItemat:IndexPath方法滚动到下一个单元格,而不是使用默认设置滚动 也就是说,每次用户向右滚动时,它将自动滚动到下一个单元格,每次用户向左滑动时,它将自动滚动到上一个单元格。无论何时滚动方向,它都会自动滚动到下一个或上一个单元格。 我尝试使用scrollViewDidScroll委托方法拦截它,但我遇到了大量的问题,它来回自动滚动并出现大量故障。我做错了什么 var

我创建了一个水平的tableView,其中的单元格占据了整个视图控制器。我希望使用scrollView.scrollToItemat: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)
                }
            }
        }
    }
}
无论何时滚动方向,它都会自动滚动到下一个或上一个单元格

为什么不扔掉所有这些代码,而是将滚动视图的isPaginEnabled设置为true?分页滚动视图自动执行您描述的操作