【发布时间】:2023-03-19 17:43:02
【问题描述】:
我制作了一个水平滚动的 UICollectionView,我希望中间的单元格具有白色字体,而其余的为黑色。
如果我只使用 scrollViewDidEndDecelerating 突出显示中间单元格似乎比我同时使用 scrollViewWillBeginDecelerating 和 scrollViewDidEndDecelerating 突出显示中间单元格更多。这是不好的做法吗?
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 上的这种效果在整个滚动过程中不断发生。
【问题讨论】:
-
动画?你是说你在突出显示一个单元格,但后来你说你在触发动画,是什么?
-
很抱歉给您带来了困惑。现在我只是根据中间的单元格更改 UICollectionCell 中 UILabel 的文本颜色。我更喜欢在用户滚动水平展开的 UICollectionCells 时为这种效果设置动画。
-
@rutgerHujismans 你能添加你正在触发的动画代码吗?
-
@rutgerhujismans 检查我的答案。
标签: ios objective-c uicollectionview