【问题标题】:Change UISegmentedControl.selectedIndex value depending on which UICollectionViewCell is currently shown根据当前显示的 UICollectionViewCell 更改 UISegmentedControl.selectedIndex 值
【发布时间】:2020-03-11 20:35:51
【问题描述】:

如何根据当前显示的 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(我开始滚动的一个和我要结束滚动的一个)可以工作。

我能做什么?

【问题讨论】:

  • 你试过collectionView(_:didUpdateFocusIn:with:)委托方法吗?
  • @AnushaKottiyal 它是如何工作的?

标签: ios swift collectionview indexpath segmentedcontrol


【解决方案1】:

以下代码似乎运行良好:

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
    segmentedControl.selectedSegmentIndex = Int(pageNumber)
}

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多