为UicollectionViews滚动不良练习



我做了水平滚动的uicollectionView,我希望中间的单元格在其余的黑色时具有白色字体。

如果我只使用中间单元格的ScrollViewDidendDecelering突出显示,似乎比我同时使用ScrollViewWillBegIndeCeleration和ScrollViewDidendDecelerationing to the Middle单元格。这是不好的做法吗?

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

此代码顺便说一句,仍然没有像我想要的那样完美地动画,因此我对如何使此滚动机制尽可能流畅地愿意。

当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的这种影响在整个滚动过程中不断发生。

在开发新动画之前,请尝试添加UILabel层的removeAllanimations():

[view.layer removeAllAnimations];

编辑:

基于您在问题中的编辑,您没有运行任何动画。您在UICollectionView上调用reloadData,这确实是不好的做法。

您应该简单:

1 :(不良选项)

仅使用PerformBatchUpdates重新加载单元格(_:postemion:)

2:好选项

使用CellForitem(:)访问单元格findCenterIndex的变量(:),只需将您的更新更新到标签。

您还可以通过获得VisibleCells数组来取消选择其他单元格,而只是在上述如上所述,但您可以启动"取消选择"代码。在运行选择代码之前,实际上可以执行此操作。或通过简单地在可见的单元格上运行循环并在循环中"取消选择",然后在您的CGPoint中心中选择一个。

这样,您甚至不必重新加载您的UicollectionView,并且是最佳实践。而且您还避免了闪烁和动画。

最新更新