0

如何根据当前显示的 UICollectionViewCell 更改 UISegmentedControl.selectedIndex 值?我的 collectionView 将isPagingEnabled 设置为 true,我可以根据 UISegmentedControl 的选定索引轻松选择不同的项目,但我该如何做相反的事情呢?

每次用户更改collectionView的页面时是否有一个函数被调用,该页面还给出了当前显示项目的indexPath?

访问 visibleCells 数组似乎没有任何用处。像这样的功能

func collectionViewDidPage(_ collectionView: UICollectionView, _ fromIndexPath: IndexPath, _ toIndexPath: IndexPath) {
    let tag = myCollectionView.cellForItem(at: toIndexPath).tag
    self.segmentedControl.selectedSegmentIndex = tag
}

其中fromIndexPathtoIndexPath是两个单元格的 indexPaths(我开始滚动的那个和我要结束滚动的那个)可以工作。

我能做些什么?

4

1 回答 1

0

以下代码似乎工作得很好:

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
    segmentedControl.selectedSegmentIndex = Int(pageNumber)
}
于 2019-11-16T22:44:59.153 回答