首页 > 解决方案 > Swift UICollectionview 水平单元格显示中心位置,并根据单元格选择自动移动

问题描述

我的场景,我正在UICollectionView使用水平滚动菜单实现。在这里,我需要显示选定的单元格自动移动到中心位置。在单元格中,我有菜单标签,我正在使用storyboard.

在我的代码下方,

extension CameraViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.reuseID, for: indexPath) as! cameraModeCollectionViewCell
        cell.cameraMode.text = self.items[indexPath.item]

        if selectedIndex == indexPath.row {
            cell.cameraMode.textColor =  colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        } else {
            cell.cameraMode.textColor =  colorLiteral(red: 0.8884977698, green: 0.3220310807, blue: 0, alpha: 0.7236373766)
        }
        return cell
    }

    // MARK: - UICollectionViewDelegate protocol
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.item)!")
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let text = self.items[indexPath.row]
        let cellWidth = text.size(withAttributes:[.font: UIFont.systemFont(ofSize: 14.0)]).width + 10.0
        return CGSize(width: cellWidth, height: collectionView.bounds.height)
    }
}

示例图像

标签: swift

解决方案


你只需要打电话scrollToItem(at:at:animated:)collectionView

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print("You selected cell #\(indexPath.item)")
    collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) //here.....
}

无需打电话reloadData()或在collectionView.


推荐阅读