滚动UICollectionViews的不良做法

时间:2017-02-16 13:14:20

标签: ios objective-c uicollectionview

我做了一个水平滚动UICollectionView,我希望中间的单元格有白色字体而其余的是黑色。

如果我只是使用scrollViewDidEndDecelerating突出显示中间单元格似乎比我使用scrollViewWillBeginDecelerating和scrollViewDidEndDecelerating突出显示中间单元格更多。这是不好的做法吗?

extension CurrencySelectorTableViewCell: UIScrollViewDelegate{
    func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
        self.findCenterIndex()
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.findCenterIndex()
    }
}

这段代码btw仍然没有完全像我想要的那样动画,所以我愿意接受任何建议,如何使这个滚动机制尽可能顺利。

当UICollectionView因此开始滚动时,会触发此功能:

func findCenterIndex() {
    let center = self.convert(self.collectionView.center, to: self.collectionView)
    let index = collectionView!.indexPathForItem(at: center)

    if let selectedIndex = index {
        self.selectedCell = selectedIndex.item
        self.collectionView.reloadData()
    }
}

重新加载UICollectionView时,位于中间的单元格中的标签看起来与其他标签不同:

func collectionView(_ collectionView: UICollectionView,
                             cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CurrencySelectorCollectionViewCell", for: indexPath) as! CurrencySelectorCollectionViewCell

    if (indexPath.item == self.selectedCell) {
        cell.currencyLabel.textColor = UIColor.white
        cell.currencyLabel.font = cell.currencyLabel.font.withSize(22)
    } else {
        cell.currencyLabel.textColor = UIColor.black
        cell.currencyLabel.font = cell.currencyLabel.font.withSize(15)
    }

    cell.currencyLabel.text = currencies[indexPath.item]

    return cell
}

现在它跳了一下,因为它只会在滚动刚开始或刚停止时更改标签。我希望UITextLabel上的这种效果在整个滚动过程中不断发生。

1 个答案:

答案 0 :(得分:1)

在发布新动画之前,尝试添加UILabel图层的removeAllAnimations()

[view.layer removeAllAnimations];

编辑:

根据您在问题中的编辑,您没有运行任何动画。您在reloadData上呼叫UICollectionView,这是非常糟糕的做法。

你应该简单:

1 :(错误选项)

仅使用performBatchUpdates(_:completion:)

重新加载单元格

2:好的选择

使用cellForItem(at:)在单元格findCenterIndex中作为变量访问单元格,只需更新标签即可。

你也可以通过获取visibleCells的数组来取消选择其他单元格,只需按照上面描述的那样进行操作,但是你可以解雇"取消选择"代码而不是。在运行选择代码之前,您实际上可以执行此操作。或者通过简单地在可见单元格上运行for循环来完成所有操作,并且取消选择"它们在您的循环中,并选择CGPoint中心的那个。

这样,您甚至不必重新加载您的UICollectionView,这是最佳做法。而你也避免闪烁和动画。