gpt4 book ai didi

ios - didSelectItemAtIndexPath 修改 UICollectionView 中的多个单元格

转载 作者:行者123 更新时间:2023-11-29 01:54:24 24 4
gpt4 key购买 nike

我有包含 30 个项目的 Collection View ,并且想在媒体上执行一些操作。我是这样做的:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

let cell = collectionView.cellForItemAtIndexPath(indexPath) as! ItemCell

var translucentView = ILTranslucentView(frame: CGRectMake(0, 0, cell.contentView.frame.size.width, cell.contentView.frame.size.height))
translucentView.translucentAlpha = 0.9
translucentView.translucentStyle = UIBarStyle.BlackTranslucent
translucentView.translucentTintColor = UIColor.clearColor()
translucentView.backgroundColor = UIColor.clearColor()
translucentView.alpha = 0.0
cell.contentView.addSubview(translucentView)
UIView.animateWithDuration(0.4, animations: {
translucentView.alpha = 1.0
})
}

该功能按预期工作,但 View 不仅出现在点击的单元格上,而且出现在屏幕上不可见的相同位置的单元格上。因此,如果屏幕上有 3 个可见单元格,我点击数字 1,那么当我滚动时, View 已添加到单元格 4、7 等...

最佳答案

UICollectionView 重复使用单元格,就像 UITableView 一样。当单元格滚动到屏幕外时,它会被添加到队列中,并将被重新用于屏幕上滚动的下一个单元格(例如单元格 4、7 ...)。

只需删除 translucentView 即可解决此问题:

UIView.animateWithDuration(0.4, animations: { () -> Void in
translucentView.alpha = 1.0
}) { (finish) -> Void in
translucentView.removeFromSuperview()
}

您可以在 ItemCell 中创建 translucentView 并在 cellForItemAtIndexPath 方法中更新其状态:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CellIdentifier, forIndexPath: indexPath) as! ItemCell

if find(collectionView.indexPathsForSelectedItems() as! [NSIndexPath], indexPath) != nil {
cell.translucentView.alpha = 1.0
} else {
cell.translucentView.alpha = 0.0
}

return cell
}

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

let cell = collectionView.cellForItemAtIndexPath(indexPath) as! ItemCell

UIView.animateWithDuration(0.4, animations: {
cell.translucentView.alpha = 1.0
})
}

override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! ItemCell

UIView.animateWithDuration(0.4, animations: {
cell.translucentView.alpha = 0.0
})
}

关于ios - didSelectItemAtIndexPath 修改 UICollectionView 中的多个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31051719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com