我创建了一个水平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)
}
}
}
}
}
最佳答案
每当滚动方向时,它应自动滚动到下一个或上一个单元格。
为什么不扔掉所有这些代码,而是将滚动视图的isPagingEnabled
设置为true
?分页滚动视图自动执行您描述的操作。
关于ios - 滑动时自动滚动到下一个/上一个单元格,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42498799/