选择单元格时如何自动将collectionviewcell滚动到最近的单元格(上一个或下一个)

Hil*_*laj 3 ios uicollectionview swift

我目前正在开发一个快速的应用程序。在一个视图控制器中,我有一个collectionView水平滚动。该collectionView是什么样子有更多的标签水平制表符。所以有些collectionViewCell's在初始时是不可见的。

我需要的是当我选择一个collectionViewCell. 我使用的是可可豆荚(SwipeMenuViewController),但它在演示中出现了一些问题。请帮助我使用 collectionView 实现相同的功能。

请查看图像以获得更清晰的信息。

在此处输入图片说明

这是我的代码

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.tabArray.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "tabCell", for: indexPath) as! tabCollectionViewCell
    cell.tabLabel.text = self.tabArray[indexPath.row]
    if selectedTabArray.contains(indexPath) {
        cell.bottomView.isHidden = false
    } else {
        cell.bottomView.isHidden = true
    }

    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    self.selectedTabArray.removeAll()
    selectedTabArray.append(indexPath)
    self.tabCollectionView.reloadData()
    tabCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)

}
Run Code Online (Sandbox Code Playgroud)

Kau*_*ana 6

您可以indexPathdidSelectItemAt方法上滚动到那个

var selectedIndex = 0

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "tabCell", for: indexPath) as! tabCollectionViewCell
    cell.tabLabel.text = self.tabArray[indexPath.item]
    if self.selectedIndex == indexpath.item {
        cell.bottomView.isHidden = false
    } else {
        cell.bottomView.isHidden = true
    }

    return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    self.selectedIndex = indexpath.item
    self.tabCollectionView.reloadData()
    tabCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
    }
Run Code Online (Sandbox Code Playgroud)

希望这有帮助!