Swift collectionView 实现双表联动效果
2022-03-05 本文已影响0人
HH思無邪
Kapture 2022-03-05 at 10.24.58.gif
如图效果 我选择左边和右边都用collectionView实现
实现这个效果,主要有两个技术点
1、点击左边item,右边滑动到对应组
2、滑动右侧列表,左边滚动到对应item
点击左边item,右边滑动到对应组第一个Item的位置
- 首先判断操作的collectionView 是否leftcollectionView
- 再次点击同样的位置 return
- 右侧collectionView滚动到指定位置
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == leftCollectView {
if currentIndex == indexPath.row {
return
}
currentIndex = indexPath.row
leftCollectView.reloadData()
leftCollectView.selectItem(at: indexPath, animated: true, scrollPosition: .top)
let collectIndexPath = IndexPath.init(row: 0, section: indexPath.row)
// 获取Section对应CollectionView布局属性
let attributes = rightCollectView.layoutAttributesForItem(at: collectIndexPath)
let point = CGPoint.init(x: 0, y: attributes?.frame.origin.y ?? 1 - rightCollectView.contentInset.top)
rightCollectView.setContentOffset(point, animated: true)
// rightCollectView.scrollToItem(at: IndexPath.init(row: 0, section: indexPath.row), at: .top, animated: true)
}
}
滑动右侧列表,左边滚动到对应item
- 获取滑动方向
private var lastoffsetY:CGFloat = 0
private var isScrollDown = true //记录滚动方向 默认true 向下
//获取 colletionView 滚动方向
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == rightCollectView {
isScrollDown = lastoffsetY < scrollView.contentOffset.y
lastoffsetY = scrollView.contentOffset.y
}
}
- 向下滚动,联动
// CollectionView item 即将展示
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if !isScrollDown && collectionView == rightCollectView && collectionView.isDragging {
//条件 为真时执行后面的代码
guard indexPath.section != currentIndex else {
return
}
scrollRowAtIndex(index: indexPath.section)
}
}
- 向上滑动 联动
// CollectionView item 即将消失
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if isScrollDown && collectionView == rightCollectView && collectionView.isDragging {
guard indexPath.section+1 != currentIndex else {
return
}
scrollRowAtIndex(index: indexPath.section+1)
}
}
- 左侧滚动
func scrollRowAtIndex(index : Int){
currentIndex = index
leftCollectView.reloadData()
leftCollectView.selectItem(at: IndexPath.init(row: index, section: 0), animated: true, scrollPosition: .bottom)
}